码迷,mamicode.com
首页 > 其他好文 > 详细

608. Two Sum - Input array is sorted【medium】

时间:2018-01-04 16:27:39      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:you   lease   pos   col   sed   div   sum   style   asc   

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.

Notice

You may assume that each input would have exactly one solution.

 
Example

Given nums = [2, 7, 11, 15], target = 9
return [1, 2]

 

解法一:

 1 public class Solution {
 2     /*
 3      * @param nums: an array of Integer
 4      * @param target: target = nums[index1] + nums[index2]
 5      * @return: [index1 + 1, index2 + 1] (index1 < index2)
 6      */
 7         public int[] twoSum(int[] nums, int target) {  
 8         int[] res = new int[]{-1, -1};  
 9           
10         int left = 0, right = nums.length - 1;  
11           
12         while (left < right) {  
13             if (nums[left] + nums[right] == target) {  
14                 res[0] = left + 1;  
15                 res[1] = right + 1;  
16                 break;  
17             } else if (nums[left] + nums[right] > target) {  
18                 right--;  
19             } else {  
20                 left++;  
21             }  
22         }  
23           
24         return res;  
25     }  
26 }

典型的双指针思路

 

608. Two Sum - Input array is sorted【medium】

标签:you   lease   pos   col   sed   div   sum   style   asc   

原文地址:https://www.cnblogs.com/abc-begin/p/8193435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!