LeetCode之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

题意分析:

给定的是一个未排序的vector整形数组和一个target,题中的排好序的数组只是一个特例。

要求在数组中找出两个数,其和等于target,且说明了这样的数字有且只有一对,所以此处不考虑找不到的情况。

也可考虑vector和multimap结合的方式。

此处排序耗费nlogn,查找耗费n,两次下标查找耗费n,总的时间复杂度为nlogn。

  1. 本题首先将原数组备份,其实就是存放好各个数字的原始位置。
  2. 将数组进行排序,然后从两头往中间靠拢,直到找到符合要求的整数对。
  3. 在备份数组中搜索这两个整数所在的位置,保存到返回结果中。

代码:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

class Solution {
public:
	vector<int> twoSum(vector<int> &numbers, int target)
	{
		int vecSize = numbers.size();
		int nStart = 0;                    //搜索的起始位置
		int nTail = vecSize-1;
		vector<int> findLoc(numbers);     //为保存原来的数组顺序
		vector<int> VerRes;               //保存返回的下标结果

		sort(numbers.begin(),numbers.end());      //先进行排序,可进行一趟搜索
		while (nStart <= nTail)
		{
			if (numbers[nStart] + numbers[nTail] < target)
			{
				nStart++;
			}
			else if (numbers[nStart] + numbers[nTail] >target)
			{
				nTail--;
			}
			else if (numbers[nStart] + numbers[nTail] == target)   //记录结果数据对在原来的vector中的位置
			{
				for (int i = 0; i< vecSize; i++)
				{
					if (numbers[nStart] == findLoc[i]  )           //查找符合要求的数字在原数组中的下标
					{
						VerRes.push_back(i+1);
						break;
					}
				}
				for (int i = 0; i< vecSize; i++)
				{
					if (numbers[nTail] == findLoc[i]  && (i+1) != VerRes[0])
					{
						VerRes.push_back(i+1);
						break;
					}
				}
				break;
			}
		}
		sort(VerRes.begin(),VerRes.end());
		return VerRes;
	}
};

int main()
{
	vector<int> num;
	vector<int> res;
	num.push_back(0);
	num.push_back(2);
	num.push_back(4);
	num.push_back(0);
	int target = 0;

	res =  Solution().twoSum(num, target);
	for (int i=0; i<res.size(); i++)
	{
		cout<<res[i]<<" ";
	}
	cout<<endl;
	system("pause");

}

时间: 2024-11-05 13:51:13

LeetCode之Two Sum的相关文章

LeetCode --- 1. Two Sum

题目链接: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. Plea

LeetCode:Range Sum Query - Immutable - 数组指定区间内的元素和

1.题目名称 Range Sum Query(数组指定区间内的元素和) 2.题目地址 https://leetcode.com/problems/range-sum-query-immutable/ 3.题目内容 英文:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 中文:给定一个数组nums,求出索引i和j之间元素的和,i一定是小于或等于j

【Leetcode】Path Sum II

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 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 思路:与[Leetcode]Path Sum 不同

LeetCode:Path Sum - 树的根节点到叶节点的数字之和

1.题目名称 Path Sum(树的根节点到叶节点的数字之和) 2.题目地址 https://leetcode.com/problems/path-sum/ 3.题目内容 英文: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. 中文:给定一颗二叉树,如

Java for LeetCode 216 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 ascending order. Example 1

LeetCode &quot;Minimum Path Sum&quot; - 2D DP

An intuitive 2D DP: dp[i][j] = min(grid[i-1][j-1] + dp[i-1][j], grid[i-1][j-1] + dp[i][j+1]) class Solution { public: int minPathSum(vector<vector<int> > &grid) { // dp[i][j] = min(dp[i-1][j] + dp[i][j], dp[i][j-1] + dp[i][j]); int n = gri

【LeetCode】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,

Leetcode:Minimum Path Sum 矩形网格最小路径和

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]Minimum Path Sum @ Python

原题地址:https://oj.leetcode.com/problems/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 r

【LeetCode OJ】Sum Root to Leaf Numbers

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 # Definition for a  binary tree node # class TreeNode: #     def __init__(self, x): #         self.val = x #         self.left = No