LeetCode-day1-两数之和(简单)

问题描述

  • 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例

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

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

题解

思路一

  • 双重循环遍历,固定一个值遍历余下所有的值求和判断是否满足
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[i] + nums[j] == target) {
                return new int[]{i, j};
            }
        }
    }
    return new int[0];
}
  • 时间复杂度 O(n^2)
  • 空间复杂度O(1)

思路二

  • for循环遍历将元素放进hash表中,以当前元素为基准判断表中是否存在构成目标数的另一个元素
public int[] twoSum2(int[] nums, int target) {
    HashMap<Integer, Integer> map = new HashMap<>();
    map.put(nums[0], 0);
    for (int i = 1; i < nums.length; i++) {
        if (map.containsKey(target - nums[i])) {
            return new int[]{map.get(target - nums[i]), i};
        }
        map.put(nums[i], i);
    }
    return new int[0];
}

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

LeetCode题目地址

posted @ 2020-05-13 11:41  丢了蜡笔的小鑫  阅读(185)  评论(0)    收藏  举报

载入天数...载入时分秒...