【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
1 2 3 4 5 6 7 8 9 10 11 12 | 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实现
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步