1. Two Sum,167. Two Sum II - Input array is sorted

来源:互联网 发布:淘宝周生生是真的吗 编辑:程序博客网 时间:2024/06/14 12:57

第一题、1. Two Sum
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].
本题不同于第二题,本题数组并不是已经排好序的,所以采用的是hash_table的数据结构,而第二题数组是已经排好序的数组,所以采用的是两个index的做法

vector<int> twoSum(vector<int>& nums, int target) {        map<int,int> mp;        vector<int> result;        for(int i= 0; i<nums.size(); i++)        {            mp[nums[i]] = i;        }        for(int i = 0; i<nums.size(); i++)        {            map<int,int> :: iterator iter;            iter = mp.find(target - nums[i]);            if(iter != mp.end() && iter->second != i) //注意此处需要加入&& iter->second != i进行判断,以防止nums[i]+nums[i]==target这种情况发生,若发生则只执行一遍循环便终止            {                if(i>iter->second)                {                    result.push_back(iter->second);                    result.push_back(i);                }                else if(i<iter->second)                {                    result.push_back(i);                    result.push_back(iter->second);                 }                break;                  }        }        //cout<<result.size()<<"hi";        return result;    }

第二题、167. Two Sum II
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

vector<int> twoSum(vector<int>& numbers, int target) {        int len = numbers.size();        int left = 1;        int right = len;        vector<int> index;        while(left < right){            if(numbers[left-1] + numbers[right-1] == target){                index.push_back(left);                index.push_back(right);                return index;            }            else if(numbers[left-1] + numbers[right-1] > target){                right--;            }            else{                left++;            }        }        return index;    }
0 0
原创粉丝点击