Created
October 26, 2012 11:15
-
-
Save binjoo/3958249 to your computer and use it in GitHub Desktop.
JAVA:面试题:请实现一个函数:凑14;输入很多个整数(1<=数值<=13),任意两个数相加等于14就可以从数组中删除这两个数,求剩余数(按由小到大排列)。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Scanner; | |
public class Test { | |
/* | |
* 请实现一个函数:凑14; 输入很多个整数(1<=数值<=13); | |
* 任意两个数相加等于14就可以从数组中删除这两个数,求剩余数(按由小到大排列); | |
*/ | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
System.out.print("输入集合长度:"); | |
String input = scan.next(); | |
int num = Integer.valueOf(input); | |
Test.exeu(num); | |
} | |
public static void exeu(int num){ | |
List<Integer> numList = Test.init(num); | |
for (int i = 0; i < numList.size();i++) { | |
int a = numList.get(i); //第一个数 | |
for (int j = i + 1; j < numList.size(); j++) { | |
int b = numList.get(j);//第二个数 | |
if(a + b == 14){ //a + b = 14满足凑14的条件,并且从集合中删除a和b | |
//System.out.println(a + " - " + b + " = " + i + " - " + j); | |
if(j > i){//判断b下标是否大于a,大于的话就先删除j,否则先删除i,防止小的删除后,下标变动。 | |
numList.remove(j); | |
numList.remove(i); | |
}else{ | |
numList.remove(i); | |
numList.remove(j); | |
} | |
i = 0;//初始化i变量,移除元素,从头开始匹配。 | |
break;//跳出 | |
} | |
} | |
} | |
System.out.print("剩余:"); | |
for (int i = 0; i < numList.size(); i++) { | |
System.out.print(numList.get(i) + " "); | |
} | |
} | |
public static List<Integer> init(int num){ | |
List<Integer> numList = new ArrayList<Integer>(); | |
System.out.print("初始:"); | |
for (int i = 0; i < num; i++) { | |
numList.add((int) (Math.random() * 13) + 1); | |
System.out.print(numList.get(i) + " "); | |
} | |
System.out.println(); | |
return numList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment