Leetcode刷题笔记(部分非原创)(1-20题)
1. Two Sum leetcode链接: https://oj.leetcode.com/problems/two-sum/ 最基础的一道题,方法很多,用HashMap存pair是一种(HashSet和HashMap的方法在这里原理是一样的)。也可以sort the whole array first,then use two pointers, one start from the left side, the other from the right side. if array[left]+array[right]>target, move the right index to the left by 1, 小于的话同理. 这里给一个HashMap的方法。 1 public int[] twoSum(int[] numbers, int target) { 2 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 3 int[] result = new int[2]; 4 for(int i = 0; i < numbers.length; i++) { 5 if(map.containsKey(numbers[i])) { 6 int index = map.get(numbers[i]);