分析
难度 易
来源
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 exactly one solution and you may not use the same element 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.
解答
1 package LeetCode; 2 import java.util.Arrays; 3 4 public class L167_TwoSumII_InputArraySorted { 5 public int[] twoSum(int[] numbers, int target) { 6 int front=0,back=numbers.length-1; 7 while(numbers[front]+numbers[back]!=target){ 8 if(numbers[front]+numbers[back]>target) 9 back--; 10 else 11 front++; 12 } 13 return new int[]{front+1,back+1};//下标计数从1开始 14 } 15 public static void main(String[] args){ 16 L167_TwoSumII_InputArraySorted l167=new L167_TwoSumII_InputArraySorted(); 17 int[] numbers = {2,7,11,15}; 18 int target = 9; 19 int[] result=l167.twoSum(numbers,target); 20 /* for (int res:result) { 21 System.out.println(res+"\t"); 22 }*/ 23 System.out.println(Arrays.toString(result)); 24 } 25 }
博客园的编辑器没有CSDN的编辑器高大上啊
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步