zoukankan      html  css  js  c++  java
  • [LeetCode]Two Sum

    今晚再刷一题,题目如下:

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    第一想法,遍历,如果numbers有n个,第1个和2,3,4,...,n比较,第2个和3,4,5,...,n比较,...,第n-1个和n个比较,当然遇到符合的就退出,复杂度O(n^2)。

    立刻意识到不需要遍历,应该用查找,遍历numbers[i]查找numbers里是否有numbers[i]-target,有则退出,否则遍历numbers[i+1].可以自己实现一个简单的平衡二叉查找树,不过直接利用map更方便,key是number。val是index。可是map的key必须是唯一的,numbers有可能有相同的数,从题目中You may assume that each input would have exactly one solution.可以推断,numbers中相同的数最多只可能有2个,所以可以把key改为number*2,遇到重复的,第二个把key记为number*2+1,但这样有个风险,输入的int型有可能溢出,提交尝试了一下,AC。结果的代码如下:

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            map<int, int> num2index;
            int n = numbers.size();
            vector<int> indexs(2, 0);
            for (int i = 0; i < n; ++i)
            {
                int current = numbers[i];
                if (num2index.find(current<<1)==num2index.end())
                {
                    num2index[current<<1] = i+1;
                }
                else
                {
                    num2index[(current<<1)+1] = i+1;
                }
            }
            for (auto it = num2index.begin(); it != num2index.end(); ++it)
            {
                int current = (it->first)>>1;
                int left = target - current;
                if (left!=current && num2index.find(left<<1) != num2index.end())
                {
                    indexs[0] = it->second;
                    indexs[1] = num2index[left<<1];
                    break;
                }
                if (left == current && num2index.find(left<<1) != num2index.end())
                {
                    if (it->second != num2index[left<<1])
                    {
                        indexs[0] = it->second;
                        indexs[1] = num2index[left<<1];
                    }
                    else
                    {
                        indexs[0] = it->second;
                        indexs[1] = num2index[(left<<1)+1];
                    }
                    break;
                }
            }
            if (indexs[1]<indexs[0])
            {
                int tmp = indexs[0];
                indexs[0] = indexs[1];
                indexs[1] = tmp;
            }
            return indexs;
        }
    };

    看了一下Dicuss,有牛人的解答,是边构造map边判断,就不需要担心key相同了,思路更清晰,效率更高,且不存在担心int溢出,Java代码如下:

    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i + 1;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i + 1);
        }
        return result;
    }
  • 相关阅读:
    _STORAGE_WRITE_ERROR_:./Application/Runtime/Cache/Home/f8995a0e1afcdadc637612fae5a3b585.php
    git 报错:没有权限 remote: error: unable to unlink old 'README.md' (Permission denied)
    深度学习入门实战(二)-用TensorFlow训练线性回归
    一条SQL搞定信息增益的计算
    Vue.js动画在项目使用的两个示例
    腾讯云安全:开发者必看|Android 8.0 新特性及开发指南
    腾讯云上Selenium用法示例
    一个只有99行代码的JS流程框架
    腾讯云上PhantomJS用法示例
    前端开发框架简介:angular和react
  • 原文地址:https://www.cnblogs.com/yezhangxiang/p/3923588.html
Copyright © 2011-2022 走看看