力扣334 递增的三元子序列
假设已经有两个数:first,second (比如first=2,second=5),我们现在希望找到一个比5大的数
遍历整个数组for(int num:nums),这个数与first,second三种关系:
如果是第一种情况:更新first,first=num
如果是第二种情况:更新second,second=num
如果是第三种情况:说明找到了递增三元序列,return true
class Solution
{
public boolean increasingTriplet(int[] nums)
{
int first=Integer.MAX_VALUE;
int second=Integer.MAX_VALUE;
for(int num:nums)
{
if(num<=first)
{
first=num;
}
//如果num>=first&&num<two
else if(num<=second)
{
second=num;
}
else//如果num>=two
{
return true;
}
}
return false;
}
}
力扣2481 n等分切割圆的最少切割次数
切半径:
切直径:
class Solution
{
//n等分的最小切割次数
//有两种切法,切半径和切直径
//结论:当n=奇数的时候,你只能切半径,不能切直径
public int numberOfCuts(int n)
{
if(n==1) return 0; //不需要切割
if(n%2==0)
{
return n/2;
}
else
{
return n;
}
}
}
力扣152 乘积最大子数组
class Solution
{
public int maxProduct(int[] nums)
{
//遍历数组,求出以每个位置元素结尾的最大乘积和最小乘积
int max=1;//以当前位置前面一个位置元素结尾的最大乘积
int min=1;//以当前位置前面一个位置元素结尾的最小乘积
int result=Integer.MIN_VALUE;
for(int i=0;i<nums.length;i++)
{
//以当前位置元素结尾的最大乘积只能是三种情况中的最大值:(1)当前元素nums[i] (2)以前一个位置元素结尾的最大乘积*当前元素 (3)以前一个位置元素结尾的最小乘积*当前元素
int curMax=Math.max(nums[i],Math.max(max*nums[i],min*nums[i]));
//以当前位置元素结尾的最小乘积只能是三种情况中的最小值:(1)当前元素nums[i] (2)以前一个位置元素结尾的最大乘积*当前元素 (3)以前一个位置元素结尾的最小乘积*当前元素
int curMin=Math.min(nums[i],Math.min(max*nums[i],min*nums[i]));
result=Math.max(result,curMax);
max=curMax;
min=curMin;
}
return result;
}
}
力扣1780 判断一个数字是否可以表示为三的幂的和
如果将数字用三进制表示:
12=(110)3 , 21=(210)3
结论:转换成三进制后,如果每一位都是0或1,没有2,那就可以表示为三的幂的和
只要有1位有2,那这个数就无法表示为三的幂的和
所以12可以,21不可以
class Solution
{
public boolean checkPowersOfThree(int n)
{
while (n != 0)
{
if (n % 3 == 2)
{
return false;
}
n /= 3;
}
return true;
}
}