LeetCode:Single Number
2015-06-24 19:49
375 查看
Single Number
Total Accepted: 74470 TotalSubmissions: 165136My Submissions
Question
Solution
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Hide Tags
Hash Table Bit
Manipulation
这个题的标准做法是利用异或运算的这两个法则:
1. a ^ b = b ^ a
2. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;
举个例子:
1^2^3^4^4^3^2的结果是啥呢?
一眼大概开不出来
根据上面两个法则,改变一下顺序吧
改成2^2^3^3^4^4^1
现在,结果一目了然了吧~
显然是1呗。
有了上面的例子,这道题就简单多了
public class Solution { public int singleNumber(int[] A) { int result = A[0]; for(int i = 1; i < A.length; i++){ result = result ^ A[i]; } return result; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)