1 two-sum

哈哈哈哈 大名鼎鼎的 two-sum ,搜索引擎上搜leetcode ,后面匹配的绝对有two -sum,作为leetcode的第一题,真是老少咸宜23333.

2333333

不废话了,上描述吧。
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, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

翻译:给你一个整数数组,返回相加为特定值的两个值的引索。可以假设每个输入只有一个解,且同一个元素不能使用两次。

设想:解法一:暴力匹配,匹配的次数是(n-1)*n/2,显然是O(N2)。实际上暴力好像也不会OutOfTime 可能是测试用例小。

解法二:利用哈希表,需要额外为O(N)的线性空间,典型的以时间换空间的策略,
用一个MAP取缓存所有不重复的NUMS[I-1]作为键,同时检验此时的num[I]来说,是否在map中存在target-nums【i】的值 如果有 就找到了,返回即可。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容