使用双指针,由于是单调递增的,所以数对是不可能重复的。
import java.util.ArrayList; import java.util.List; public class TwoNumSum { public static void main(String[] args) { int nums[]={1,2,3,4,5,6,7,8,9,10}; List<NumberPair> theTwoNums = new TwoNumSum().findTheTwoNums(nums, 10); theTwoNums.forEach(x->System.out.println(x.num1+","+x.num2)); } public List<NumberPair> findTheTwoNums(int[] nums,int target){ List<NumberPair> list=new ArrayList<>(); int left=0; int right=nums.length-1; while(left<right){ if(nums[left]+nums[right]==target){ list.add(new NumberPair(nums[left],nums[right])); left++; right--; }else if(nums[left]+nums[right]<target){ left++; }else if(nums[left]+nums[right]>target){ right--; } } return list; } } class NumberPair{ public int num1; public int num2; public NumberPair(int num1,int num2){ this.num1=num1; this.num2=num2; } }