`

Find a duplicate element in an array

XOR 
阅读更多

Question:

Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice. Assume that you can access each element of the array only once. Describe an algorithm to find the repeated number. If you used auxiliary storage in your algorithm, can you find an algorithm that does not require it?

 

如果可以用辅助空间的话,可以用HashSet来处理,如果add失败说明有重复的。但是如果不能用额外空间的话呢?

 

Solution 1:

考虑加法。1+2+...+n = n(n-1)/2

假设数组所有元素之和为sum, 那么sum-n(n-1)/2就是我们要找的重复的数。

public int findDuplicate(int[] nums) {
	int sum = 0;
	int n = nums.length;
	int expected = n*(n-1)/2;
	for(int i=0; i<n; i++) {
		sum += nums[i];
	}
	return sum-expected;
}

但是数组的元素数达到或接近INT_MAX的时候, 加法运算就会溢出。我们还可以考虑位运算XOR。

XOR具有以下性质:

交换律A \oplus B = B \oplus A

结合律A \oplus (B \oplus C)=(A \oplus B) \oplus C

恒等律X\oplus 0=X

归零律X\oplus X=0

自反A \oplus B \oplus B=A\oplus 0=A

假设给定数组A[6] = {5,2,3,4,3,1},而我们期望的数组应该为A[6]={0,1,2,3,4,5}。其中我们用0来代替重复的元素。

接下来对给定数组和我们期望数组的所有元素做异或运算:

(5^0)^(2^1)^(3^2)^(4^3)^(3^4)^(1^5)

= (5^5)^(2^2)^(3^3)^(4^4)^(1^1)^(3^0)

= 0^3

= 3

写成代码则非常简单。

Solution2:

public int findDuplicate(int[] nums) {
	int dup = 0;
	for(int i=0; i<nums.length; i++) {
		dup ^= nums[i]^i;
	}
	return dup;
}

Reference:

http://stackoverflow.com/questions/2605766/how-to-find-a-duplicate-element-in-an-array-of-shuffled-consecutive-integers 

分享到:
评论

相关推荐

    java-leetcode题解之Find the Duplicate Number.java

    java java_leetcode题解之Find the Duplicate Number.java

    Here are a few algorithmic problems for you to try: Problem 1:

    Given a sorted array of integers, write a function to find the first duplicate in the array. Example: input = [1, 2, 3, 4, 5, 2, 3] -&gt; output = 2 Problem 3: Given a binary tree, write a function to...

    javalruleetcode-DataStructures:使用面向对象的方法和单元测试用例在Java中实现各种数据结构

    element in the array. //How can you sort an array and remove duplicate entries. A few questions on Big O efficiency. Questions on memory management. * //Implement a HashMap. Try to stick to the syntax...

    C语言实验作业

    2. Write a program that reads ten numbers supplied by the user into a 2 by 5 array, and then prints out the maximum and minimum values held in: (a) each row (2 rows) (b) the whole array 3.Use a...

    duplicate-array:复制一个数组

    这个主题,也就是我们所说的“duplicate-array”,涉及到数组的深拷贝和浅拷贝概念,这对于理解JavaScript中的引用类型至关重要。下面我们将深入探讨这个知识点。 首先,我们要知道在JavaScript中,数组是一种特殊...

    Manyprog Find Duplicate Files 2.5 Multilingual.rar

    这款Manyprog Find Duplicate Files软件功能强大全面,简单易操作,使用后可以帮助用户更轻松快捷的查找并删除重复文件。软件可以帮助用户查找计算机上的重复文件,并根据需要进行清理,非常的方便,还能节省存储...

    Vistanita Duplicate Finder

    5. Distribute Vistanita Duplicate Finder in any other form than in the official distribution packages without a written permission from the Author. 6. Use the licensed version of Vistanita Duplicate ...

    FindDuplicate:简单HTML游戏可查找重复项

    【FindDuplicate: 简单HTML游戏可查找重复项】 在网页开发中,HTML(超文本标记语言)是构建网页的基础。"FindDuplicate"是一款基于HTML的轻量级游戏,旨在帮助用户锻炼记忆力和观察力,通过找出重复的元素来完成...

    Duplicate Email Remover 2.7

    Duplicate Email Remover (Add-In for Microsoft Outlook 2000/XP/2003): README ============================================ Please read this file carefully (especially "Installation" chapter) before ...

    find_dup_1.zip_Duplicate Text

    "find_dup_1.zip_Duplicate Text"这个项目就是针对这个问题的一个实例。它使用了一种名为`find_dup.awk`的Awk脚本来查找和处理文本文件中重复的行。Awk是一种强大的文本分析工具,尤其适用于处理结构化数据,如CSV或...

    先进的前端拖放页面生成器:elementor

    无论您是网站开发新手还是专业设计师,Elementor都提供了直观的工具和界面,使您能够轻松设计和构建美观的网站。它支持任何WordPress主题、任何页面和任何设计。Elementor是一个强大的工具,可帮助您将创意转化为...

    数据库系统概念第六版答案(包括实践习题,习题)下载

    make sure there are no duplicate names in the result. •Find the IDs and names of all students who have not taken any course offering before Spring 2009. 11 •For each department, find the maximum ...

    FindDupFile

    Fast Duplicate File Finder is a powerful utility for finding duplicate files in a folder and all its sub folders. The duplicate remover has the following features: Find DUPLICATE files or find ...

    ORACLE Duplicate复制数据库

    ### ORACLE RMAN DUPLICATE 数据库复制详解 #### 概述 在Oracle环境中,通过RMAN(Recovery Manager)工具可以高效地复制整个数据库。本文将详细介绍如何利用RMAN的`DUPLICATE`命令来实现数据库的复制,并针对两种...

    Algorithms in C++, Parts 1-4: Fundamentals, Data Structures, Sorting, Searching

    Key operations include `find` (determining which subset an element belongs to) and `union` (merging two subsets into one). 4. **Perspective**: The chapter provides a perspective on the importance of...

    Duplicate File Cleaner 2.5.4.168注册码

    在提供的部分内容中,“DuplicateFileCleaner2.5.4.168ע:5ע.DC-3B08-5568-LEPIODWHK5DC-D56A-5588-HGJPKDJRM5DC-C7D7-5538-RDWEDDVJJ5DC-61CA-55C8-BNHGWDRFD5DC-0401-5548-GUPXSDITP5”看似是一系列注册码的示例...

    FirmTools Duplicate Photo Finde

    FirmTools Duplicate Photo Finder 相似图像查询软件 你电脑中如果有很多图像,有很多可能是一个logo只差,你用其他md5检测软件是不能快速找出来的。这个软件可以搜索相似的图像,你查看后选择删除,非常的方便。 ...

Global site tag (gtag.js) - Google Analytics