【LeetCode】167. Two Sum II - Input array is sorted

Difficulty:easy

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/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.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactlyone solution and you may not use the sameelement 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.

Intuition

refer to 和为s的两个数字

 

Solution

    public int[] twoSum(int[] num, int target) {
        int i=0, j=num.length-1;
        while(i<j){
            if(num[i]+num[j]<target)
                i++;
            else if(num[i]+num[j]>target)
                j--;
            else
                return new int[]{i+1,j+1};
        }
        return null;
    }

  

Complexity

Time complexity : O(n)

Space complexity : O(1)

 

What I've learned

1.The use of two pointers.

 

 More:【目录】LeetCode Java实现

 

posted @ 2018-11-22 09:06  华仔要长胖  阅读(304)  评论(0编辑  收藏  举报