Posted onEdited onInLeetCodeDisqus: Symbols count in article: 231Reading time ≈1 mins.
O(n) time O(1) space 利用下标从0到n,把所有数异或最后剩下的就是差的数
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intmissingNumber(vector<int>& nums){ int n = nums.size(); int res = n; for (int i = 0; i < n; ++i) { res ^= (i ^ nums[i]); } return res; } };
Posted onEdited onInLeetCodeDisqus: Symbols count in article: 863Reading time ≈1 mins.
greedy O(n) time - best! 计算每个位置所能到达的最远的位置(选择最远的,即贪心),并维护一个全局当前可以到达的最远位置,如果当前的位置比当前的全局可以到达的最远位置还要远,证明当前位置无法达到,那么最后一个位置也不可能从第一个位置到达
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: boolcanJump(vector<int>& nums){ int n = nums.size(); for (int i = 0, curr_max = 0; i < n && curr_max < n - 1; ++i) { if (i > curr_max) returnfalse; curr_max = max(curr_max, i + nums[i]); } returntrue; } };