zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[LeetCode] Two Sum

LeetCode sum two
2023-09-14 09:01:04 时间
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 targe
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

/*****************************************************************************

 * @COPYRIGHT NOTICE

 * @Copyright (c) 2015, 楚兴

 * @All rights reserved

 * @Version : 1.0

 * @Author : 楚兴

 * @Date : 2015/2/5 13:40

 * @Status : Accepted

 * @Runtime : 22 ms

*****************************************************************************/

#include iostream 

#include vector 

#include algorithm 

using namespace std;

class Solution {

public:

 vector int twoSum(vector int numbers, int target) {

 vector int indices;

 vector int temp(numbers);

 sort(numbers.begin(),numbers.end());

 for (int i = 0; i numbers.size() - 1; i++)

 for (int j = i + 1; j numbers.size(); j++)

 if (numbers[i] + numbers[j] == target)

 int n1 = find(temp,numbers[i]);

 int n2 = find(temp,numbers[j], n1 - 1);

 if (n1 n2)

 indices.push_back(n1);

 indices.push_back(n2);

 else

 indices.push_back(n2);

 indices.push_back(n1);

 return indices;

 if (numbers[i] + numbers[j] target)

 break;

private:

 int find(vector int num, int n, int flag = -1)

 for (int i = 0; i num.size(); i++)

 if (i == flag)

 continue; //不能和前一个点序号相同

 if (num[i] == n)

 return i + 1;

int main()

 vector int nums;

 nums.push_back(2);

 nums.push_back(7);

 nums.push_back(11);

 nums.push_back(14);

 Solution s;

 vector int indices = s.twoSum(nums,9);

 return 0;

}

// Runtime: 28 ms

class Solution {

public:

 vector int twoSum(vector int nums, int target) {

 unordered_map int, int mymap;

 vector int indices;

 for (int i = 0; i nums.size(); i++)

 if (mymap.find(target - nums[i]) != mymap.end())

 indices.push_back(mymap[target-nums[i]] + 1);

 indices.push_back(i + 1);

 else

 mymap[nums[i]] = i;

 return indices;

};


LeetCode - #1 Two Sum 我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。微博:@故胤道长)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not
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 tr