1. LeetCode 1


Answer key: In this example, we use HashMap to store the current nums[I] as key and index subscript as value in the map. During the saving process, we can determine whether the target value minus the current cycle value already exists in the map. Map. get(key), key = target-nums [I] (target = nums[I]) (target = nums[I]) Understand and think of using HashMap. HashMap is very useful in solving many problems.

  public static int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(target - nums[i])) {

            return new int[]{map.get(target - nums[i]), i};

        }
        map.put(nums[i], i);

    }
    return nums;
Copy the code

2. Merge two ordered linked lists

Each time you recurse to compare the current value of l1 and L2, the next node will always join the smaller value, the end condition is l1 and L2 either null.

public ListNode mergeTwoLists1List(ListNode l1, ListNode l2) { if(l1==null){ return l2; } if(l2==null){ return l1; } if(l1.val<l2.val){ l1.next=mergeTwoLists1List(l1.next,l2); return l1; }else{ l2.next=mergeTwoLists1List(l1,l2.next); return l2; }}Copy the code

LeetCode 11

Answer key: The loop goes from both ends to the middle, I ++ and j– is it I ++ or j– and it’s easier to understand that if you compare a[I] with a[j], because you need the most, you must move the smaller values of a[I] and a[j] to the middle, Because I’m not sure if I’m going to get anything bigger than the current value, so I’m going to use Max every time and the maximum value is the most water, and when I find the middle, Max is the maximum value and I’m going to return it. You have to write it in a familiar way.

public static int maxArea(int a[]) {
    int max = 0;
    for (int i = 0, j = a.length - 1; i < j; ) {
        int moveMinBar = a[i] < a[j] ? a[i++] : a[j--];
        max = Math.max(max, (j - i + 1) * moveMinBar);

    }
    return max;
}
Copy the code

4. Move zero LeetCode 283

Nums [I] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] = nums[j] After the first loop, the length of the array minus the length of the value I minus j is how many 0’s there are, and then we go from j to I and we add 0’s at the end of the loop. You need to know the solution the first time and be able to write it independently the next time.

Public static void moveZeroes(int[] nums) {public static void moveZeroes(int[] nums) {public static void moveZeroes(int[] nums) { for (int num : nums) { if(num! =0){ nums[j]=num; j++; For (int I =j; int I =j; i<nums.length; i++){ nums[i]=0; }}Copy the code