TwoSum

作者: yixinfeng | 来源:发表于2016-10-17 14:26 被阅读0次

题目描述:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

我的解答:

public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        int[] result = new int[2];
        int num = nums.length;
        for(int i=0;i<num;i++){
            if(map.containsKey(nums[i])){
                int index = map.get(nums[i]);
                result[0] = index;
                result[1] = i;
            }else{
                map.put(target-nums[i], i);
            }
        }
        return result;
    }

分析:

  • 一开始尝试使用循环遍历的方法,虽然很容易想到,但是测试未通过,原因是时间复杂度为O(N^2)。参考了下网上的解法,主要思路是通过一个HashMap来实现,map里存放的键值对是(target-nums[index],index),从i=0开始去查找map里面是否存在nums[i],如果不存在,就把(target-nums[i],i)放入map,这样如果查找到这个值,说明在之前有匹配的数,而且之前存入的index号是互补数的index。

相关文章

  • TwoSum

    题目大意: 找到数组中两个元素相加等于指定数的所有组合 情况一:给定数组中不含重复元素,且均为正整数 思路: 使用...

  • twoSum

    Problem Given an array of integers, return indices of the...

  • TwoSum

    刷题当然要从TwoSum开始了~~python刷题果然容易~~~class Solution(object):de...

  • TwoSum

    介绍:Two Sum给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。函数 twoSum 返回这两个相...

  • TwoSum

  • TwoSum

    Problem### Given an array of integers, find two numbers s...

  • TwoSum

    简单方法,两边循环,一个推着另一个,复杂度n2 使用map,检查过的存起来map,每拿到一个新的,就去map里查,...

  • TwoSum

    题目描述: Given an array of integers, return indices of the t...

  • twoSum

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。 你需要实现的函数twoSum需要返回这两个...

  • TwoSum

    暴力暴力算法时间复杂度O(n²),空间复杂度O(1) 两次遍历 HashMap时间复杂度:O(n),我们把包含有 ...

网友评论

      本文标题:TwoSum

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