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;
        }
    };
  • 相关阅读:
    C++
    C语言获取系统时间的几种方式
    我在学习编程中犯的两个最大错误
    《十天学会单片机和C语言编程》
    socket 编程通信实例
    比尔·盖茨给年轻人的十一个忠告 句句是哲理
    程序员有八个级别。
    DOS debug 命令的详细用法
    从命令行模式运行Windows管理工具。
    无法删除DLL文件解决方法(转)
  • 原文地址:https://www.cnblogs.com/jdneo/p/4783211.html
Copyright © 2011-2022 走看看