【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;
    }
};
时间: 2024-08-02 00:39:49

【LeetCode】2. Two Sum的相关文章

【Leetcode】Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:简单的动态规划题目,设f(m, n)为从(0, 0)到达(m

【LeetCode】113. Path Sum II 基于Java和C++的解法及分析

113. Path Sum II Total Accepted: 80509 Total Submissions: 284188 Difficulty: Medium Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8

【LeetCode】Minimum Path Sum 解题报告

[题目] Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. [思路] 求从左上角到右下角的最小路径值,典型的动态规划

【LeetCode】1. Two Sum 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280 Subject 出处:https://leetcode.com/problems/two-sum/ 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

【LeetCode】039. Combination Sum

题目: Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers

【LeetCode】167. Two Sum II - Input array is sorted

Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascending order, 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 a

【LeetCode】040. Combination Sum II

题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be

【LeetCode】112 - Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode】363. Max Sum of Rectangle No Larger Than K

题目描述: Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k. 解题思路: 根据题意,寻找二维数组中所有可以组成的矩形中面积不超过k的最大值,所以必须要求出可能组成的矩形的面积并与k比较求出最终结果.这里为了最终不超时,可以在一下方面进行优化: 1.设置一个数组比较当前列(或

【LeetCode】216. Combination Sum III

Combination Sum III Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Ensure that numbers within the set are sorted in ascend