當前位置:
首頁 >
leetcode33 --- search
發布時間:2024/7/23
41
豆豆
生活随笔
收集整理的這篇文章主要介紹了
leetcode33 --- search
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 題目
整數數組 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,5,6,7] 在下標 3 處經旋轉后可能變為?[4,5,6,7,0,1,2] 。
給你 旋轉后 的數組 nums 和一個整數 target ,如果 nums 中存在這個目標值 target ,則返回它的下標,否則返回?-1?。
你可以設計一個時間復雜度為?O(log n)?的解決方案嗎?
2 思路
題目要求時間復雜度為?O(log n), 那么就需要用二分法的方法來. 雖然整個序列并不是有序的, 但是二分之后必然有一邊是有序的, 所以二分之后檢查目標是否在有序的一邊, 并重新確定左右邊界, 循環下去.
代碼:
int search(vector<int>& nums, int target) {int res_index = -1;int nums_size = nums.size();if (nums_size > 0) {int left_idx = 0;int right_idx = nums_size - 1;while (left_idx < right_idx) {if (nums[left_idx] == target)return left_idx;if (nums[right_idx] == target)return right_idx;int check_index = (left_idx + right_idx) / 2;if (nums[check_index] == target)return check_index;bool left_inorder = nums[left_idx] < nums[check_index];bool target_in_inorder = left_inorder ?(target <= nums[check_index] && target >= nums[left_idx]) :(target <= nums[right_idx] && target >= nums[check_index + 1]);if (target_in_inorder) {left_idx = left_inorder ? left_idx : check_index + 1;right_idx = left_inorder ? check_index : right_idx;} else {left_idx = left_inorder ? check_index + 1 : left_idx;right_idx = left_inorder ? right_idx : check_index;}}if (nums[left_idx] == target)return left_idx;}return res_index;}?
總結
以上是生活随笔為你收集整理的leetcode33 --- search的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果电脑mac_清理Mac苹果电脑DNS
- 下一篇: docker harbor 域名_doc