leetcode Two Sum 兩數之和 第二題

第一種解法:暴力破解

時間複雜度O(n2), 空間複雜度O(1)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = {0,0};
        for(int i = 0; i < nums.length - 1; i++ ){
            for(int j = i + 1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }
}

第二種解法:使用HashMap求解

時間複雜度O(n), 空間複雜度O(1)

思路:在map中使用nums[i],作爲key,使用i作爲value,先用 target - nums[i],查看差值是否存在map中,若不存在,則將當前數值put到map中。

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章