Fork me on github

1-两数之和

import java.util.HashMap;
import java.util.Map;

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

使用map可将时间复杂度降为O(n)

posted @ 2020-07-01 22:56  zjy4fun  阅读(130)  评论(0编辑  收藏  举报