Last active
December 14, 2015 01:09
-
-
Save dzwillpower/5004406 to your computer and use it in GitHub Desktop.
问题描述:给定包含101个元素的数组arr,数组中元素一定属于[1,100],并且[1,100]之间的每个数都在arr中出现过。 解决方案:分析,数组中有101个元素,如果[1,100]之间的每个数出现一次,那就是100个元素了,剩下的那个元素就是唯一的重复出现的元素。我们可以通过遍历arr,得到arr中所有元素的总和,然后既然[1,100]之间的每个数出现一次,那么我们减去1+2+……+99+100的和,结果就是我们需要的唯一的重复出现的元素了。时间复杂度是O(n)。
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
package com.wits.practice; | |
/** | |
* 找出数组中唯一的重复元素 | |
* @author dzwillpower | |
* 2013-2-21下午08:27:56 | |
*/ | |
public class FindOnlyRepeat { | |
public static void main(String[] args) { | |
int[] array =new int[]{1,2,3,4,4,5,6,7,8,9,10,11}; | |
System.out.println("repeat num: "+findRepeat(array)); | |
} | |
/** | |
* 找数组中的重复元素 | |
* @param arr | |
* @return | |
*/ | |
public static int findRepeat(int[] arr){ | |
int temp_sum = 0;//记录1-100之间的和 | |
int total_sum = 0;// 记录所有11个数的和 | |
int i = 0; | |
while(i < 11){ | |
temp_sum +=i+1; | |
total_sum +=arr[i++]; | |
} | |
temp_sum -=11; | |
return total_sum-temp_sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment