leet-code/src/main/java/leetcode/editor/cn/MissingNumber.java
huangge1199@hotmail.com 118eef14fb 268:丢失的数字
2021-07-18 13:57:24 +08:00

79 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。
//
//
//
// 进阶:
//
//
// 你能否实现线性时间复杂度、仅使用额外常数空间的算法解决此问题?
//
//
//
//
// 示例 1
//
//
//输入nums = [3,0,1]
//输出2
//解释n = 3因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。
//
// 示例 2
//
//
//输入nums = [0,1]
//输出2
//解释n = 2因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。
//
// 示例 3
//
//
//输入nums = [9,6,4,2,3,5,7,0,1]
//输出8
//解释n = 9因为有 9 个数字,所以所有的数字都在范围 [0,9] 内。8 是丢失的数字,因为它没有出现在 nums 中。
//
// 示例 4
//
//
//输入nums = [0]
//输出1
//解释n = 1因为有 1 个数字,所以所有的数字都在范围 [0,1] 内。1 是丢失的数字,因为它没有出现在 nums 中。
//
//
//
// 提示:
//
//
// n == nums.length
// 1 <= n <= 104
// 0 <= nums[i] <= n
// nums 中的所有数字都 独一无二
//
// Related Topics 位运算 数组 哈希表 数学 排序
// 👍 415 👎 0
package leetcode.editor.cn;
//268:丢失的数字
class MissingNumber {
public static void main(String[] args) {
//测试代码
Solution solution = new MissingNumber().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int missingNumber(int[] nums) {
int xor = 0;
for (int i = 0; i <= nums.length; i++) {
xor^=i;
}
for (int num : nums) {
xor^=num;
}
return xor;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}