leetcode 1-10 题解记录

1. Two Sum [Easy]

思路

水题

要点

  1. map用法: put, get, containsKey
  2. 声明数组new int[]{1, 2};
  3. 异常情况还需要返回值的话, 抛IllegalArgumentException

代码

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]

猜你喜欢

转载自www.cnblogs.com/tanglizi/p/11493520.html
今日推荐