public class Solution { public int[] twoSum(int[] nums, int target) { int temp; boolean flag = false; int[] index = new int[2]; for(int i = 0; i < nums.length; i++){ temp = target - nums[i]; for(int j = 0; j < nums.length; j++){ if(i == j) continue; if(temp == nums[j]){ index[1] = j+1; flag = true; break; } } if(flag){ index[0] = i+1; break; } } return index; } 思路二: 把数组的值作为map的key, 由于满足 nums[i] + nums[j] = target ,故必存在key值满足nums的元素 public int[] twoSum2(int[] nums, int target) { int[] index=new int[2]; HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); for(int i = 0; i<nums.length; i++) { if(hm.containsKey(target - nums[i])) { index[1] = i+1; index[0] = hm.get(target-nums[i])+1; return index; }else { hm.put(nums[i],i); } } return index; } }
原文地址:http://blog.csdn.net/xu758142858/article/details/46238979