classSolution{publicint[]twoSum(int[] nums,int target){int n = nums.length;for(int i =0; i < n -1; i++){for(int j = i +1; j < n; j++){if(nums[i]+ nums[j]== target){returnnewint[]{i,j};}}}returnnewint[0];}}
方法二:哈希表
classSolution{publicint[]twoSum(int[] nums,int target){
HashMap<Integer,Integer> map =newHashMap<>();for(int i =0; i < nums.length; i++){
map.put(nums[i],i);}for(int i =0; i < nums.length; i++){int complement = target - nums[i];if(map.containsKey(complement)&& map.get(complement)!= i){returnnewint[]{i, map.get(complement)};}}returnnewint[0];}}
方法三:哈希表优化
classSolution{publicint[]twoSum(int[] nums,int target){
HashMap<Integer,Integer> map =newHashMap<>();for(int i =0; i < nums.length; i++){int complement = target - nums[i];if(map.containsKey(complement)){returnnewint[]{i, map.get(complement)};}
map.put(nums[i],i);}returnnewint[0];}}