【Leetcode】【Python】【C++】1. Two Sum实现

来源:互联网 发布:淘宝天猫投诉电话人工 编辑:程序博客网 时间:2024/05/16 17:36

题目:

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 would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


思路:

temp数组存放nums数组中对应位置的需要值,e.g. nums中第一个元素nums[ 0 ]为2,那么这个元素对应target的目标值为9-2=7,那么把这个值放入temp中即temp[ 0 ];当遍历到nums中的元素nums[ j ] 和temp中的某个元素temp[ i ]相等时,也就意味着前面我们需要的元素已经找到,那么此时,temp[ i ] + nums[ j ] = target。在本例中,nums中遍历到的下一个元素是nums[ 1 ] = 7, 他和temp[ 0 ]相等,也就是说我们找到了相加为target所需要的值。这时候nums[ 0 ] + nums[ 1 ] = 9,程序应返回i,j,这里为0,1.


实现:

#include#includeusing namespace std;class Solution {public:vector twoSum(vector& nums, int target){vectortemp;int num = nums.size();vectorresult;temp.push_back(-9999);for (int i = 0; i < num; i++){for (int j = 0; j < temp.size(); j++){if (nums[i] == temp[j]){result.push_back(j-1);result.push_back(i);return result;}}temp.push_back(target - nums[i]);}}};int main(){vector res;vector test;int target = 0;test.push_back(0);test.push_back(4);test.push_back(3);test.push_back(0);Solution A;res = A.twoSum(test, target);for (int i = 0; i < res.size(); i++){cout << res[i] << endl;}cin.get();return 0;}


原创粉丝点击