【leetcode】268. Missing Number
2016-04-21 11:09
375 查看
题目:
Given an array containing n distinct numbers taken from
For example,
Given nums =
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
翻译:
数组nums中的数字的取值是0-n,且都不重复,只是从中去掉了一个数字,本题的任务是要找出这个缺失的数。且最好只能用一个额外的空间。
思路:
本题的思路有很多种,其他好想的我就不说了,我就说说用位的异或操作来实现的做法,这个做法我觉得网上大部分博客说的不太清楚。首先我们知道:
1.A^0=A
2.异或操作是满足交换律,结合律。
首先我们令result=0^1^...^n,然后我们对整个数组进行遍历,令result=result^nums[i],那么根据结合律和交换律,我们相当于进行了这样的操作(假设确实的数是i):(0^0)^(1^1)...((i-1)^(i-1))^(i)^((i+1)^(i+1))...(n^n),那么最后的结果就是缺失的数i。
代码:
Given an array containing n distinct numbers taken from
0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums =
[0, 1, 3]return
2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
翻译:
数组nums中的数字的取值是0-n,且都不重复,只是从中去掉了一个数字,本题的任务是要找出这个缺失的数。且最好只能用一个额外的空间。
思路:
本题的思路有很多种,其他好想的我就不说了,我就说说用位的异或操作来实现的做法,这个做法我觉得网上大部分博客说的不太清楚。首先我们知道:
1.A^0=A
2.异或操作是满足交换律,结合律。
首先我们令result=0^1^...^n,然后我们对整个数组进行遍历,令result=result^nums[i],那么根据结合律和交换律,我们相当于进行了这样的操作(假设确实的数是i):(0^0)^(1^1)...((i-1)^(i-1))^(i)^((i+1)^(i+1))...(n^n),那么最后的结果就是缺失的数i。
代码:
class Solution { public: int missingNumber(vector<int>& nums) { int result = nums.size(); int i=0; for(int num=0;num<nums.size();num++){ result ^= nums[num]; result ^= i; 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----Longest Substring Without Repeating Characters
- [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_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- 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 题解