[Algorithm-Java implementation] Find numbers that only appear once
1. Problem description:
Given an array of non-empty integers, except for an element that appears only once, all other elements appear twice. Look for the element that appears only once.
such as:
Input: [2,2,1]; Output: 1
Input: [1,2,2,3,4,3,4]; Output: 1
2. Question answer:
Ideas: XOR operation
Since the elements in this question only appear once and twice, the optimal solution is to perform XOR operations on the array elements .
What is XOR operation?
To put it simply, if two numbers are different, the XOR result is 1; if two numbers are the same, the XOR result is 0 . XOR means that it is not equal to 1, and equal to 0.
Features of XOR operation:
1. Perform an exclusive OR operation on any number and 0, and the result is the original number, that is, a^0=a
2. Perform XOR operation on any number and itself, the result is 0, that is, a^a=0
3. The exclusive OR operation satisfies the commutative and associative laws
Source of this question: LeetCode136
First, define an int type variable singleNumber=0, then traverse the array, perform XOR operation with singleNumber in turn, and finally return singleNumber.
For example: input [2,2,1] , singleNumber is initialized to 0.
singleNumber is 0, and 2 is XORed to get 2;
singleNumber is 2, and then XOR with 2 to get 0;
singleNumber is 0, and then calculate with 1 to get 1.
3. Algorithm analysis:
1. Time complexity is O(N): traverse the array
2. The extra space complexity is O(1): no extra space is used.
code show as below
import java.util.Scanner;
class Solution {
//测试方法
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String[] strArray = str.split(",");
int[] nums = new int[strArray.length];
for(int i=0;i<nums.length;i++) {
nums[i]=Integer.parseInt(strArray[i]);
}
int result = singleNumber(nums);
System.out.println(result);
}
//实现方法
public static int singleNumber(int[] nums) {
int singleNumber = 0;
for (int num : nums) {
singleNumber ^= num;
}
return singleNumber;
}
}