leetcode.com/problems/single-number/

 

Single Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

Input: nums = [2,2,1]
Output: 1

n^2으로 비교해주는 법 hashMap을 이용하여 n으로 비교해주는 법 등 다양한 방법이 있지만
비트연산의 같은 숫자가 짝수번일때 0이 되는 성질을 이용하여 다음과 같이 풀이하였다.

class Solution {
 	public int singleNumber(int[] nums) {
		int answer = 0;
		
		for (int i : nums) {
			answer ^= i;
		}
		
		return answer;
	}
}

+ Recent posts