广东建设职业技术学院官方网站,重庆优化网站公司,如何找网站开发人员,网站宝二级域名怎么设置两数之和 简单题
思路#xff1a;一个Map#xff0c;key是数值#xff0c;value是该数值对应的下标#xff0c;遍历的时候判断一下当前数组下标对应的值在map里有没有可组合成target的#xff08;具体体现为在map里找target-nums【i】)#xff0c;如果有#xff0c;直接…两数之和 简单题
思路一个Mapkey是数值value是该数值对应的下标遍历的时候判断一下当前数组下标对应的值在map里有没有可组合成target的具体体现为在map里找target-nums【i】)如果有直接返回没有的话就加进去继续找。
需要掌握的方法map的get和containsKey cl
ass Solution {public int[] twoSum(int[] nums, int target) {MapInteger,Integer m new HashMap();m.put(nums[0],0);for(int i 1;inums.length;i){if(m.containsKey(target - nums[i])){return new int[]{m.get(target-nums[i]),i};}else{m.put(nums[i],i);}}return new int[0];}
}
三数之和 双指针 中等题 思路严格上来说算三个指针一个i是维护当前遍历到的数字下标之后的l和r指针是从i所处位置开始在i 1 到len - 1这个区间中寻找nums[i]的相反数。
class Solution {// -4 -1 -1 0 1 2 // public ListListInteger threeSum(int[] nums) {ListListInteger res new ArrayList();Arrays.sort(nums);int len nums.length;if(len 2){return res;}for(int i 0;i len;i){int l i 1;int r len - 1;if( i ! 0 nums[i] nums[i-1]){//与前一个数重复需要调过不然会出现重复的三元组continue;}while(l r){if(nums[i] nums[l] nums[r] 0){if(l i 1 nums[l] nums[l-1] ){//这里也是同理l ;continue;}ListInteger tmp new ArrayList();tmp.add(nums[i]);tmp.add(nums[l]);tmp.add(nums[r]);l;r--;//左右指针都要变因为l变大的话还希望结果有可能为0r必须变小意味着nums[r]变小)res.add(tmp);}else if(nums[i] nums[l] nums[r] 0){//nums[l] 太小了把它变大一点l ;} else{r --;}}}return res;}
}