Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

1. Two Sum #76

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

Sol.1复杂度不够好 public class Solution { public int[] twoSum(int[] nums, int target) { //Arrays.sort(nums); List list = new ArrayList<>(); for(int i = 0; i < nums.length-1; i++) { for(int j = 1; j < nums.length; j++) { if(nums[i] == target - nums[j]&& i != j) { list.add(i); list.add(j); } } } int[] res = new int[2]; for(int i = 0; i < 2; i++) { res[i] = list.get(i); } return res; } } Sol.2 hashmap public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); int[] res = new int[2]; for(int i = 0; i < nums.length; i++) { if(map.containsKey(target-nums[i])) { res[0] = map.get(target-nums[i]); res[1] = i; } map.put(nums[i], i); } return res; } }

Shawngbk commented 7 years ago

Amazon