王廷瑋|數位醫療|智慧醫療: 81. Search in Rotated Sorted Array II WFU

2024年7月5日 星期五

81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II


給定一個按非遞減順序排序的整數數組 nums(不一定是唯一值)。

在傳遞給你的函數之前,nums 在未知的旋轉點 k(0 <= k < nums.length)處旋轉,使得結果數組為 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](0 索引)。例如,[0,1,2,4,4,4,5,6,6,7] 可能在旋轉點索引 5 處旋轉並變為 [4,5,6,6,7,0,1,2,4,4]。

給定旋轉後的數組 nums 和一個整數 target,如果 target 存在於 nums 中則返回 true,否則返回 false。

你必須儘可能減少整體操作步驟。

範例 1:

輸入:nums = [2,5,6,0,0,1,2], target = 0 輸出:true


Python


from typing import List

class Solution:
def search(self, nums: List[int], target: int) -> bool:
left, right = 0, len(nums) - 1

while left <= right:
mid = (left + right) // 2

if nums[mid] == target:
return True

# If the left half is sorted
if nums[left] < nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1

# If the right half is sorted
elif nums[left] > nums[mid]:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1

# If nums[left] == nums[mid], we have to deal with duplicates
else:
left += 1

return False

17.32MB, 52ms


C++


#include <vector>

class Solution {
public:
bool search(std::vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;

while (left <= right) {
int mid = left + (right - left) / 2;

if (nums[mid] == target) {
return true;
}

// If the left half is sorted
if (nums[left] < nums[mid]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// If the right half is sorted
else if (nums[left] > nums[mid]) {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// If nums[left] == nums[mid], we have to deal with duplicates
else {
left++;
}
}

return false;
}
};

16.52MB, 3ms


Javascript

/**
* @param {number[]} nums
* @param {number} target
* @return {boolean}
*/
var search = function(nums, target) {
let left = 0;
let right = nums.length - 1;

while (left <= right) {
let mid = Math.floor((left + right) / 2);

if (nums[mid] === target) {
return true;
}

// If the left half is sorted
if (nums[left] < nums[mid]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// If the right half is sorted
else if (nums[left] > nums[mid]) {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// If nums[left] == nums[mid], we have to deal with duplicates
else {
left++;
}
}

return false;
};

49.04MB, 48ms