File tree Expand file tree Collapse file tree
src/main/java/com/algorithm/study/demo/algorithm/leetcode Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .algorithm .study .demo .algorithm .leetcode ;
2+
3+ /**
4+ * 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
5+ *
6+ * 说明:
7+ *
8+ * 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
9+ *
10+ * 示例 1:
11+ *
12+ * 输入: [2,2,1]
13+ * 输出: 1
14+ * 示例 2:
15+ *
16+ * 输入: [4,1,2,1,2]
17+ * 输出: 4
18+ *
19+ * 来源:力扣(LeetCode)
20+ * 链接:https://leetcode-cn.com/problems/single-number
21+ */
22+ public class Solution20 {
23+
24+ /**
25+ * 任何数字跟自己进行异或都等于0,0跟任何数字异或都等于该数字本身。
26+ * 所以把数组中的数字进行异或最后得到的肯定是一个不重复的数字,因为重复的数字都是两两出现。
27+ * 公式:a^b^a=b
28+ * @param nums
29+ * @return
30+ */
31+ public static int singleNumber (int [] nums ) {
32+ if (nums .length ==0 ){
33+ return -1 ;
34+ }
35+ if (nums .length ==1 ){
36+ return nums [0 ];
37+ }
38+ int result =0 ;
39+ for (int num :nums ){
40+ result ^= num ;
41+ }
42+ return result ;
43+ }
44+
45+ public static void main (String [] args ) {
46+ System .out .println (singleNumber (new int []{2 , 2 , 1 }));
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments