LintCode第485题-生成给定大小的数组,第220题-冰雹猜想,第235题-分解质因数
第485题
描述
给你一个大小size,生成一个元素从1 到 size
的数组
样例 1:输入: size = 4输出: [1, 2, 3, 4]样例解释: 返回一个顺序填充1到4的数组。样例 2:输入: size = 1输出: [1]样例解释: 返回一个顺序填充1到1的数组
代码如下:
public class Solution {
/**
* @param size: An integer
* @return: An integer list
*/
public List<Integer> generate(int size) {
// write your code here
List<Integer> integerList=new ArrayList<>();
for(int i=1;i<=size;i++)
{
integerList.add(i);
}
return integerList;
}
}
第220题
描述
数学家们曾提出一个著名的猜想——冰雹猜想。
对于任意一个自然数N,如果N是偶数,就把它变成N / 2;
如果N是奇数,就把它变成 3 * N+1。
按照这个法则运算下去,最终必然得1。
试问,该数通过几轮变换,会变成1呢?
1<=n<=1000
样例 1:
输入:
4
输出:
2
解释:
第一轮:4/2=2
第二轮:2/2=1
答案为2
代码如下:
public class Solution {
/**
* @param num: an integer
* @return: an integer
*/
public int getAnswer(int num) {
// write your code here.
int goal=num;
int count=0;
while(goal>1)
{
if(goal%2==0)
{
goal=goal/2;
}else
{
goal=goal*3+1;
}
count++;
}
return count;
}
}
第235题:
描述
将一个整数分解为若干质因数之乘积
你需要从小到大排列质因子
样例 1:
输入:10
输出:[2, 5]
样例 2:
输入:660
输出:[2, 2, 3, 5, 11]
代码如下:
public class Solution {
/**
* @param num: An integer
* @return: an integer array
*/
public List<Integer> primeFactorization(int num) {
// write your code here
int temp=num;
List<Integer> resultList=new ArrayList<>();
if(temp==1)
{
return new ArrayList<>();
}
for(int i=2;i<=Math.sqrt(temp);i++)
{
while(temp%i==0)
{
resultList.add(i);
temp=temp/i;
}
}
if(temp>1)
{
resultList.add(temp);
}
return resultList;
}
}