leetcode 1-10 solution to a problem record

1. Two Sum [Easy]

Thinking

Water problem

Points

  1. map用法: put, get, containsKey
  2. Statement array new int [] {1, 2};
  3. Unusual circumstances also need to return a value, then throw IllegalArgumentException

Code

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map=new HashMap();
        
        for (int i=0; i<nums.length; i++){
            int tmp=target-nums[i];
            if (map.containsKey(tmp)){
                int idx=map.get(tmp);
                if (i!=idx) return new int[]{idx, i};
            }map.put(nums[i], i);
        }
        throw new IllegalArgumentException();
    }
}

2. Add Two Numbers [Medium]

Guess you like

Origin www.cnblogs.com/tanglizi/p/11493520.html