LeetCode题解:Missing Number
2015-09-24 10:14
127 查看
题目链接:
Missing Number题目描述:
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?
题目解释:
给定一个数组,数组中的元素取自0~n,而且元素各不相同,找到数组中缺失的那个元素。例如:一个数组中有三个元素0,1,3,那么这个数组实际上是从0~3中取的数,缺失的那个数字就是2.
这里要注意一点:数组中的元素不一定是有序的,0 1 3,的顺序也可以是 3 1 0,这样的数组的输出结果是一样的。
解题方案:
这个题目要求线性的时间复杂度,我最初的想法是将这个数组排序,然后再从头遍历,遇到的那个数组元素跟下标索引不一致的元素,将这个减一就是Missing Number.现在来看,我们最初的想法是不可以的了,那怎么办呢,只能用空间换取时间了,我们令开辟一个n大小(这里的n就是取数范围0~n的n)的布尔型数组,然后采用哈希的思想,将数字k标注在array[k]的位置,如果k存在,那么array[k]为true,遍历完第一遍以后,再从头遍历一边,找出array[i]为false的元素,此时缺失的元素就是i。
当然这里不要忘记初始化咱们的布尔型数组,初始值设为false
这种方法虽然有点LOW,但是还是AC了哈哈,先看这个方法实现的代码:
int missingNumber(int* nums, int numsSize) { bool isHave[numsSize]; for (int i = 0; i < numsSize; ++i) { isHave[i] = false; } for (int i = 0; i < numsSize; ++i) { isHave[nums[i]] = true; } for (int i = 0; i < numsSize; ++i) { //isHave[nums[i]] = true; if(isHave[i] == false) { return i; } } return numsSize; }
这样的题目,很明显还有更好的方法,比如位运算,只是我们想不到具体的实现,我就去网上检索了,下面这个方法是网上的,我还是没整明白这个位运算是,哎,先把代码贴上来吧,留个笔记:
int missingNumber(int* nums, int numsSize) { int n = 0; for (int i = 0; i < numsSize; ++i) { n ^= (i+1) ^ nums[i]; } return n; }
位运算是硬伤呀,哀叹~
相关文章推荐
- 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_linearList
- leetcode_linearList02
- 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 题解