1. 程式人生 > >leetcode-167-Two Sum II-Input array is sorted

leetcode-167-Two Sum II-Input array is sorted

asc tco indices cto quest sea input 完成 cif

題目描述:

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)

說明:

1、數組不降序(在測試樣例中見過輸入是一連串的0),給定目標,找到兩個數的和為目標,返回這兩個數的坐標。坐標要小的在前,大的在後,從1開始。

2、題目保證必定能找到這樣的兩個元素滿足條件,且同一個元素不能用兩次。

3、題目要求看到這裏,最初始的想法是雙重循環,這種做法能夠把這道題作出來,但是提交之後超時了。

4、既然簡單粗暴的雙重循環不行,那就單層循環+二分查找。提交完之後擊敗21.32%的cpp submissions,看來還有優化的空間。這裏有個地方要註意一下,不能使用條件numbers[i]<=target,因為numbers裏面的數不一定都是正數。

5、到discuss區看一下大神的做法,看到了一個簡潔的代碼如下。

vector<int> twoSum(vector<int>& numbers, int
target)
{
int lo=0, hi=numbers.size()-1; while (numbers[lo]+numbers[hi]!=target)
  {
if (numbers[lo]+numbers[hi]<target)
     { lo
++; }
     else
    { hi--; } } return vector<int>({lo+1,hi+1}); }

  代碼來自於leetcode用戶allbugs(反向毒奶?)。侵刪。

  這種做法可以說是很簡潔了。單層循環+二分查找還是有點浪費時間,沒有很好地利用二分查找過程中積累的信息。

  這種算法打敗了56.40%的cpp submissions。

  附上筆者本人的代碼,供感興趣的朋友參考。

代碼:(單層循環+二分查找)

  int binarysearch(vector<int>& nums,int a,int b)
    {int min=b+1,max=nums.size()-1;//從b+1開始找,排除同一個元素用兩次的情況,並且節省時間
        int mid=(min+max)/2;
        while(min<=max)
        {
            if(nums[mid]==a)
                return mid;
            if(nums[mid]<a)
            {
                min=mid+1;
            }
            else
            {
                max=mid-1;
            }
            mid=(min+max)/2;
        }
        return -1;//如果沒有找到返回-1
    }
    vector<int> twoSum(vector<int>& numbers, int target) 
    {int j;
        for(int i=0;i<numbers.size();i++)
        {
            j=binarysearch(numbers,target-numbers[i],i);if(j!=-1)
            {
                if(i>j)
                {
                    vector<int>result{j+1,i+1};return result;
                }
                else if(i<j)
                {
                    vector<int>result{i+1,j+1};return result;
                }
            }
        }    
    }

leetcode-167-Two Sum II-Input array is sorted