两数之和
暴力
双层循环 两两相加 等于目标值 返回 即可
class Solution {public int[] twoSum(int[] nums, int target) {for(int i=0;i<nums.length;i++){for(int j=0;j<nums.length;j++){if(nums[i]+nums[j]==target && i!=j){int[] a={i,j};return a;}}}return null;}
}
map
class Solution {public int[] twoSum(int[] nums, int target) {HashMap<Integer,Integer> map=new HashMap();int[] res=new int[2];for(int i=0;i<nums.length;i++){int a=target-nums[i];if(map.get(a)==null){map.put(nums[i],i);}else{res[0]=i;res[1]=map.get(a); }}return res;}
}
快慢指针
class Solution {public int[] twoSum(int[] nums, int target) {//快速排序 O(nlogn)int[] copy=new int[nums.length];for(int t=0;t<nums.length;t++){copy[t]=nums[t];}Arrays.sort(nums);int[] res=new int[2];//快慢指针int j=nums.length-1;int i=0;while(i<nums.length){if(i==j){return null;}if(nums[i]+nums[j]<target){i++;}else if(nums[i]+nums[j]>target){j--;}else{res[0]=i;res[1]=j;break;}}if(res[0]!=0||res[1]!=0){Boolean m=true;Boolean q=true;for(int k=0;k<nums.length;k++){if(copy[k]==nums[res[0]]&& m){res[0]=k;m=false;}else if(copy[k]==nums[res[1]] && q){res[1]=k;q=false;}}}return res;}
}
作者声明
如有问题,欢迎指正!