美文网首页
LeedCode(1) 两数之和

LeedCode(1) 两数之和

作者: 桃花岛张岛主 | 来源:发表于2019-08-13 09:31 被阅读0次

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

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

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 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(target == nums[j] + nums[i])
                    return new int[]{j,i};
            }
        }
        return null;
    }
}
image.png

分析: 时间复杂度:O(n2),因为用到双重循环。
空间复杂度:O(1)

思路二:通过上一中解法的复杂度分析,如果有更好的解法,应该是时间复杂度要低一些,这时我们立马想到hash这种数据结构,一种典型的空间换取时间的做法,这也是比较常规的做法,代码如下:

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

分析:时间复杂度O(n)
空间复杂度O(n)

相关文章

  • LeedCode(1) 两数之和

    题目如下:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并...

  • LeedCode15:三数之和

    LeedCode15:三数之和 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,...

  • 1、两数之和

    https://leetcode-cn.com/problems/two-sum/[https://leetcod...

  • 1,两数之和

    2019.5.15 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标...

  • 1 两数之和

    文|Seraph 01 | 问题 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目...

  • 1、两数之和

    题目 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数...

  • 【1】两数之和

    题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并...

  • [LeetCode] 索引

    1. 两数之和

  • leetcode top100

    1.求两数之和(数组无序) 2.求电话号码的字母组合 3.三数之和 4.两数之和(链表)

  • 【LeetCode通关全记录】1. 两数之和

    【LeetCode通关全记录】1. 两数之和 题目地址:1. 两数之和[https://leetcode-cn.c...

网友评论

      本文标题:LeedCode(1) 两数之和

      本文链接:https://www.haomeiwen.com/subject/dzgmjctx.html