comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
中等 |
|
给你一个仅由整数组成的有序数组,其中每个元素都会出现两次,唯有一个数只会出现一次。
请你找出并返回只出现一次的那个数。
你设计的解决方案必须满足 O(log n)
时间复杂度和 O(1)
空间复杂度。
示例 1:
输入: nums = [1,1,2,3,3,4,4,8,8] 输出: 2
示例 2:
输入: nums = [3,3,7,7,10,11,11] 输出: 10
提示:
1 <= nums.length <= 105
0 <= nums[i] <= 105
题目给定的数组
我们定义二分查找的左边界
在每一步中,我们取中间位置
如果
时间复杂度
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) >> 1
if nums[mid] != nums[mid ^ 1]:
r = mid
else:
l = mid + 1
return nums[l]
class Solution {
public int singleNonDuplicate(int[] nums) {
int l = 0, r = nums.length - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] != nums[mid ^ 1]) {
r = mid;
} else {
l = mid + 1;
}
}
return nums[l];
}
}
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] != nums[mid ^ 1]) {
r = mid;
} else {
l = mid + 1;
}
}
return nums[l];
}
};
func singleNonDuplicate(nums []int) int {
l, r := 0, len(nums)-1
for l < r {
mid := (l + r) >> 1
if nums[mid] != nums[mid^1] {
r = mid
} else {
l = mid + 1
}
}
return nums[l]
}
function singleNonDuplicate(nums: number[]): number {
let [l, r] = [0, nums.length - 1];
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] !== nums[mid ^ 1]) {
r = mid;
} else {
l = mid + 1;
}
}
return nums[l];
}
impl Solution {
pub fn single_non_duplicate(nums: Vec<i32>) -> i32 {
let mut l = 0;
let mut r = nums.len() - 1;
while l < r {
let mid = (l + r) >> 1;
if nums[mid] != nums[mid ^ 1] {
r = mid;
} else {
l = mid + 1;
}
}
nums[l]
}
}
int singleNonDuplicate(int* nums, int numsSize) {
int l = 0, r = numsSize - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] != nums[mid ^ 1]) {
r = mid;
} else {
l = mid + 1;
}
}
return nums[l];
}