leetcode 167 Two sum II inout array is sorted

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.

Note:

  • 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.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

 /*
            思路 ; 1、暴力法;依然是一个可行解; 没有充分利用数组有序这个特性;
                2、有序:二分查找; nums[i] + target[nums[i]]==target;

                3、最优:双索引技术
     */

class Solution {
    /*
    
        思路 ; 暴力法;依然是一个可行解; 没有充分利用数组有序这个特性;
                有序:二分查找; nums[i] + target[nums[i]]==target;
                
    
    */
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        int n=nums.size();
        vector<int>result;
        if(n<=1)
            return result;
        int left=0;
        int right=n-1;
        while(left<right)//[left...right]中找出两个数之和==target
        {
            int sum=nums[left]+nums[right];
            if(sum==target)
            {
                int res[2]={left+1,right+1};
                return vector<int>(res,res+2);//数组和动态数组之间的转换关系;
            }
            else
            {
                if(sum>target)
                    right--;
                else 
                    left++;
            }     
        }
        //return result;
    }
};

猜你喜欢

转载自blog.csdn.net/langxue4516/article/details/81348941