leetcode33 --- search
1 題目
整數(shù)數(shù)組 nums 按升序排列,數(shù)組中的值 互不相同 。
在傳遞給函數(shù)之前,nums 在預(yù)先未知的某個(gè)下標(biāo) k(0 <= k < nums.length)上進(jìn)行了 旋轉(zhuǎn),使數(shù)組變?yōu)?[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下標(biāo) 從 0 開始 計(jì)數(shù))。例如, [0,1,2,4,5,6,7] 在下標(biāo) 3 處經(jīng)旋轉(zhuǎn)后可能變?yōu)?[4,5,6,7,0,1,2] 。
給你 旋轉(zhuǎn)后 的數(shù)組 nums 和一個(gè)整數(shù) target ,如果 nums 中存在這個(gè)目標(biāo)值 target ,則返回它的下標(biāo),否則返回?-1?。
你可以設(shè)計(jì)一個(gè)時(shí)間復(fù)雜度為?O(log n)?的解決方案嗎?
2 思路
題目要求時(shí)間復(fù)雜度為?O(log n), 那么就需要用二分法的方法來. 雖然整個(gè)序列并不是有序的, 但是二分之后必然有一邊是有序的, 所以二分之后檢查目標(biāo)是否在有序的一邊, 并重新確定左右邊界, 循環(huá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;}?
總結(jié)
以上是生活随笔為你收集整理的leetcode33 --- search的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果电脑mac_清理Mac苹果电脑DNS
- 下一篇: flutter字体不跟随系统_Flutt