LeetCode1: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

一、题目描述

基本意思是已知一个整数数组,和一个特定的目标常数target,要求找出整数数组中两个数之和等于target,结果输出这两个数的下标。

二、解题思路

思路1:暴力解决,即先在数组中固定一个数字,再依次判断数组中其余的n-1个数字与它的和是不是等于target,这种方法的空间复杂度为O(1),时间复杂度为O(n^2);
思路2:先新建一个数组,用来保存原数组的值和下标索引,然后对数组按值进行排序,最后利用头指针i和尾指针j找到两个数使得他们的和等于target。
struct Node
{
	int num, pos;  //保存原数组的值和下标索引
};
bool cmp(Node a, Node b)
{
	return a.num < b.num; //自定义升序排序
}
class Solution {
public:
	vector<int> twoSum(vector<int> &numbers, int target) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		vector<int> result;
		vector<Node> array;
		for (int i = 0; i < numbers.size(); i++)
		{
			Node temp;
			temp.num = numbers[i];
			temp.pos = i;
			array.push_back(temp);
		}

		sort(array.begin(), array.end(), cmp); //先将数组按从小到大排序

		//利用头指针i和尾指针j找到两个数使得他们的和等于target
		for (int i = 0, j = array.size() - 1; i != j;)
		{
			long long  sum = array[i].num + array[j].num;//两个int的加和可能溢出int,因此sum提升为long long 再进行比较更鲁棒。
			if (sum == target)
			{
				if (array[i].pos < array[j].pos)
				{
					result.push_back(array[i].pos + 1);
					result.push_back(array[j].pos + 1); //以1为起始下标
				}
				else
				{
					result.push_back(array[j].pos + 1);
					result.push_back(array[i].pos + 1);
				}
				break;
			}
			else if (sum < target)
			{
				i++;
			}
			else if (sum > target)
			{
				j--;
			}
		}
		return result;
	}
};



 
   
LeetCode1:Two Sum_第1张图片

你可能感兴趣的:(LeetCode1:Two Sum)