题解 | #和为S的两个数字#
和为S的两个数字
https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b
import java.util.*; import java.util.ArrayList; public class Solution { public ArrayList<Integer> FindNumbersWithSum1(int [] array,int sum) { int end_cur=array.length-1; while(end_cur>=0){ if(array[end_cur]>=sum){ end_cur--; }else{ break; } } ArrayList<Integer> rst=new ArrayList<>(); //确定了数组取值的 label1:for(int cur=end_cur;cur>=0;cur--){ for(int cur_1=0;cur_1<cur;cur_1++){ if(array[cur]+array[cur_1]==sum){ rst.add(array[cur]); rst.add(array[cur_1]); break label1; } } } return rst; } public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum){ ArrayList<Integer> list=new ArrayList<Integer>(); if(array==null||array.length<2) return list; int head=0; int tail=array.length-1; while(head<tail){ if(array[head]+array[tail]==sum){ list.add(array[head]); list.add(array[tail]); return list; }else if(array[head]+array[tail]>sum){ tail--; }else{ head++; } } return list; } }