一:每日一题:分糖果
今天的题目是一道简单题。主要思想:1.用哈希表存储当前的糖果种类数目。2.妹妹的糖果种类数目最多是糖果数除二。
class Solution {
public int distributeCandies(int[] candyType) {
HashMap<Integer,Integer> sister=new HashMap<Integer,Integer>();
int result=0;
for(int i=0;i<candyType.length;i++){
if(sister.get(candyType[i])==null){
sister.put(candyType[i],1);
result++;
}
if(result>=candyType.length/2){
return candyType.length/2;
}
}
return result;
}
}
二: 双指针题目:三数之和
这个题目的主要思想分为两个部分:
1.避免重复枚举:首先是先排序(原因很直观),接着是遍历数组需要考虑的问题,因为是三个数字和为0,那么只要确定了两个数字,第三个数字必定唯一。即把三个数字抽象为x、y、z,阵对x或者y,每个值只遍历一次。
2.将复杂度为N平方:直观思想便是三层遍历,那样的话时间复杂度是N的三次方,
因为已经排好序,且x、y固定时,z唯一。对于y和z,用双指针来求。z初始话为length-1.向左遍历,y向右遍历,直到y大于或者x+y+z=0(注意此时只会有这两种情况),对于重复问题,我们在遍历到第一个是结果的z的时候会跳出,不是结果的z会继续跳过,不需要像x和y一样专门考虑。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> resutlt=new ArrayList<List<Integer>>();
Arrays.sort(nums);
if(nums.length==0||nums[nums.length-1]<0||nums[0]>0){
return resutlt;
}
for(int i=0;i<nums.length;i++){
int x=nums[i];
if(i>0&&x==nums[i-1]){
continue;
}
int k=nums.length-1;
for(int j=i+1;j<nums.length;j++){
if (j >i+1&&nums[j] == nums[j-1]){
continue;
}
while(j<k&&nums[j]+nums[k]+x>0){
k--;
}
if(k==j){
break;
}
if(nums[j]+nums[k]+x==0){
ArrayList<Integer>list=new ArrayList<Integer>();
list.add(x);
list.add(nums[j]);
list.add(nums[k]);
resutlt.add(list);
//break;//
}
}
}
return resutlt;
}
}