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;
        }
    };
  • 相关阅读:
    jquery实现章节目录效果
    Delphi里如何让程序锁定在桌面上,win+d都无法最小化
    php 之跨域上传图片
    delphi判断文件类型
    EmptyRecycle() 清空回收站
    delphi检查url是否有效的方法
    Explode TArray
    css设置中文字体(font-family:"黑体")后样式失效问题
    javascript-lessons
    课后作业2
  • 原文地址:https://www.cnblogs.com/jdneo/p/4783211.html
Copyright © 2011-2022 走看看