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;

}

}

相关推荐
QiLinkOS1 小时前
第三视觉理解徐玉生与他的商业活动(28)
大数据·c++·人工智能·算法·开源协议
wabs6662 小时前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月2 小时前
54.螺旋矩阵
java·算法·leetcode·矩阵
Robot_Nav3 小时前
MPPI 局部规划器实验设计讲解
人工智能·算法·mppi
mingo_敏3 小时前
Mean-Teacher 均值教师自训练框架详解
算法·均值算法
星空露珠4 小时前
迷你世界UGc3.0脚本Wiki[剧情动画模块管理接口 Timeline]
开发语言·数据结构·算法·游戏·lua
笨笨没好名字4 小时前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode
jinyishu_4 小时前
常见排序算法详解
数据结构·算法·排序算法
手写码匠4 小时前
手写 LLM 安全护栏:从内容审核到越狱防御的完整实现
人工智能·深度学习·算法·aigc
luj_17684 小时前
草酸与烟酸对消化及糖代谢的影响解析
服务器·c语言·开发语言·经验分享·算法