我有一个数组,除了一个元素外,所有元素都重复了:
int[] a={2,6,6,2,4,1,4};
如何找到未成对的整数元素?
我有一个数组,除了一个元素外,所有元素都重复了:
int[] a={2,6,6,2,4,1,4};
int result = 0;
for(int i : a)
result ^= i;
计算未配对的元素。(为了获取未配对元素的索引,你需要再次遍历数组,查找result
。)
O(N)
的空间。 - Cratyluspublic static void main( String[] args ) {
int[] a = { 2, 6, 6, 2, 4, 1, 4 };
Map<String, Integer> counts = new HashMap<String,Integer>();
String key;
for ( int i : a ) {
key = String.valueOf( i );
if ( counts.containsKey( key ) ) {
int count = counts.get( key );
counts.put( key, ++count );
}
else {
counts.put( key, 1 );
}
}
for ( Map.Entry<String, Integer> entry : counts.entrySet() ) {
if ( entry.getValue() < 2 ) {
System.out.println( entry.getKey() + " does not have a pair" );
}
}
}
int
转换成String
,只需要使用Map<Integer,Integer>
就可以了。 =) - Demetrio Neto在Codility示例中列出了一个例子,我在那里测试了这个代码,并发现对于某些测试用例存在一些不正确性和性能问题。