twoSum

作者: Lee_java | 来源:发表于2020-10-14 09:33 被阅读0次
//给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 
//
// 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 
//
// 
//
// 示例: 
//
// 给定 nums = [2, 7, 11, 15], target = 9
//
//因为 nums[0] + nums[1] = 2 + 7 = 9
//所以返回 [0, 1]
// 
// Related Topics 数组 哈希表 
// 👍 9326 👎 0


import java.util.HashMap;
import java.util.Map;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>(nums.length);
        int len = nums.length;
        int start = 0;
        int end = 0;
        for (int i=0;i<len;i++){
            map.put(nums[i],i);
        }
        for (int i=0;i<len;i++){
            start = i;
            end = target - nums[i];
            if (map.get(end) != null){
                return new int[]{start,map.get(end)};
            }
        }
        return new int[]{};

    }
}
//leetcode submit region end(Prohibit modification and deletion)

相关文章

  • 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/byyipktx.html