zoukankan      html  css  js  c++  java
  • 【LeetCode】2. 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

    提示:

    此题非常常见,解决思路通常可以有两种,一种是使用哈希表,其时间复杂度为O(n),另一种是对数组进行排序,时间复杂度是O(nlogn)。不过实际执行下来是第二种的耗时更少。所以有时候在数据规模不大的时候,系数也是挺关键的一个因素。

    代码:

    哈希表方法:

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int> map;
            int n = (int)nums.size();
            for (int i = 0; i < n; i++) {
                auto p = map.find(target-nums[i]);
                if (p!=map.end()) {
                    return {p->second+1, i+1};
                }
                map[nums[i]]=i;
            }
        }
    };

     排序方法:

    class Solution
    {
    public:
        vector<int> twoSum(vector<int>& numbers, int target)
        {
            vector<int> tmpNumbers(numbers.begin(), numbers.end());
            sort(tmpNumbers.begin(), tmpNumbers.end());
    
            int val1 = -1;
            int val2 = -1;
            int i = 0;
            int j = tmpNumbers.size() - 1;
            while(i < j) {
                if(tmpNumbers[i] + tmpNumbers[j] < target) ++i;
                else if(tmpNumbers[i] + tmpNumbers[j] > target) --j;
                else {
                    val1 = tmpNumbers[i];
                    val2 = tmpNumbers[j];
                    break;
                }
            }
    
            vector<int> result;
            for(int i = 0; i < numbers.size(); ++i) {
                if(numbers[i] == val1 || numbers[i] == val2) result.push_back(i + 1);
                if(2 == result.size()) return result;
            }
            return result;
        }
    };
  • 相关阅读:
    2012年浙大:Hello World for U
    noip2011普及组:统计单词
    noip2013提高组:积木大赛
    蓝桥杯:错误票据
    C#知识点
    疑问
    C#多态
    SQLServer导入Excel,复杂操作
    SQLServer数据库基本操作,导入Excel数据
    C#基础学习
  • 原文地址:https://www.cnblogs.com/jdneo/p/4783211.html
Copyright © 2011-2022 走看看