如题:
Find out duplicate number between 1 to N numbers.
描述:
You have got a range of numbers between 1 to N, where one of the number is repeated. You need to write a program to find out the duplicate number.
代码:
package test;
import java.util.ArrayList;
import java.util.Iterator;
/*
* You have got a range of numbers between 1 to N, where one of the number is repeated.
* You need to write a program to find out the duplicate number.
*/
public class DuplicateNumber {
/*
* 1, 2, 2, 3, 4 ---- Duplicated List
* Sum(Duplicated List) - 4*5/2 = 2
*/
public int findDuplicatNumber(ArrayList<Integer> numberList){
// If there exists a duplicated number, the biggest number in the list is size-1;
int biggestNum = numberList.size() - 1;
// 2S = n*(n+1)
int duplicatedNum = sumList(numberList) - biggestNum*(biggestNum+1)/2;
return duplicatedNum;
}
// get the summation of the list
public int sumList(ArrayList<Integer> numberList){
int sum = 0;
for (int num : numberList) {
sum += num;
}
return sum;
}
public static void main(String[] args) {
ArrayList<Integer> numberArrayList = new ArrayList<Integer>();
for (int i = 1; i <= 20; i++) {
numberArrayList.add(i);
}
numberArrayList.add(10);
DuplicateNumber dumTest = new DuplicateNumber();
System.out.println(dumTest.findDuplicatNumber(numberArrayList));
}
}
使用数组的前N项和公式,然后根据连续的特性,利用差值求出数组中重复的数据。
要点
1. Java数组的ArrayList使用方法
2. 数组求和的方法