leetcode 167 Two Sum II - Input 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. 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
題目的輸入是一個已經按照升序排列的整數數組和一個目標數字。
要求的輸出是:數組中加和剛好爲目標數字的兩個元素的位置(這裏的位置不從0開始計算)。
同時題目假設每組輸入剛好只有一個答案,而且不能重複使用同一元素。

理解

這道題是能夠用兩層循環蠻力解決的,可是效率過低了。咱們如何能獲得一個複雜度爲n的解法呢?
咱們能夠聲明兩個指針left,right分別指向數組中最小的元素、最大的元素。
若是這兩個元素和大於目標數組,right指針左移;若是小於,left指針右移。若是等於,則返回這兩個元素的位置(記得用數組的index數值加一)數組

解法

public int[] twoSum(int[] numbers, int target) {

        int[] res = new int[2];
        if(numbers == null || numbers.length <2){
            return res;
        }
        
        int left = 0;
        int right = numbers.length-1;        
        while(left < right){
            int temp = numbers[left] + numbers[right];
            if(temp == target){
                res[0] = left + 1;
                res[1] = right +1;
                return res;
            }else if(temp >target){
                right --;
            }else{
                left++;
            }
        }
        
        
        return res;
    }
相關文章
相關標籤/搜索