[LeetCode]1.两数之和

题目描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum

暴力法

时间复杂度 O ( n 2 ) O(n^2) O(n2)
空间复杂度 O ( 1 ) O(1) O(1)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

使用哈希表

时间复杂度 O ( n ) O(n) O(n)
空间复杂度 O ( n ) O(n) O(n)

两遍哈希表

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap();
        //第一遍循环填充数组
        for(int i = 0; i < nums.length; i++){
            map.put(nums[i],i);
        }
        //第二遍循环查询map
        for(int i = 0; i < nums.length; i++){
            int complement = target - nums[i];
            if(map.containsKey(complement) && map.get(complement) != i){
                return new int[]{ i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

一遍哈希表

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap();
        //一次遍历
        for(int i = 0; i < nums.length; i++){
            int complement = target - nums[i];
            if(map.containsKey(complement) && map.get(complement) != i){
                return new int[]{i, map.get(complement)};
            }
            map.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum Solution");
    }
}

总结

HashMap是常数级的查找效率,遍历数组时可以用target减去当前的数组元素,这样就得到了另一个元素值,只需要查找这个值是否在HashMap中即可

  • 获取数组长度:nums.lengths
  • 创建并初始化数组: new int[]{i,j}
  • map.containsKey(Object key) 查询map中是否包含指定key
  • map.get(Object key) 返回Key值所指定的value
posted @ 2019-11-18 22:07  消灭猕猴桃  阅读(60)  评论(0编辑  收藏  举报