LeetCode 1. two sum

来源:互联网 发布:台湾网络主播萱萱 编辑:程序博客网 时间:2024/06/18 16:52

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].
answer:
class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> couple;        vector<int> result;        //vector<int>::iterator it = nums.begin();        int itID = 0;        couple.push_back(target - nums[itID]);        itID ++;        while(itID != nums.size()){                int iterID = 0;                while(iterID != couple.size()){                    if(couple[iterID] == nums[itID]) {                        result.push_back(iterID);                        result.push_back(itID);                        return result;                    }                    iterID ++;                }                couple.push_back(target - nums[itID]);                itID ++;        }    }};



0 0
原创粉丝点击