标签:new out [] lse print string tor || iterator
题目一:输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,输出任意一对即可。
import java.util.*; public class FindSumNumber{ public ArrayList<Integer> getSumNumber(int[] array,int sum){ if(array == null || array.length == 0 || sum <= 2) return null; int num1 = 0; int num2 = 0; int head = 0; int end = array.length-1; ArrayList<Integer> list = new ArrayList<Integer>(); while(head < end){ int temp = array[head]+array[end]; if(temp == sum){ num1 = array[head]; num2 = array[end]; break; } else if(temp<sum){ head++; }else{ end--; } } if(head < end){ list.add(num1); list.add(num2); } return list; } public static void main(String[] args){ int[] array = {1,2,4,7,11,15}; FindSumNumber f = new FindSumNumber(); ArrayList<Integer> list = f.getSumNumber(array,16); Iterator<Integer> iter = list.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } } }
标签:new out [] lse print string tor || iterator
原文地址:https://www.cnblogs.com/yingpu/p/9256546.html