leetcode 33.Search in Rotated Sorted Array 旋转数组二分查找法搜索

题目来源leetcode33.SearchinRotatedSortedArray地址:点击打开链接代码classSolutionpublic:intsearch(vector<int>&nums,inttarget)intn=nums.size();intfirst=0;intlast=n-1;intmid=first (last-first)/2;if(nums[mid]=...

leetcode 33.Search in Rotated Sorted Array 旋转数组二分查找法搜索

题目来源leetcode�33.Search in Rotated Sorted Array 地址:点击打开链接

代码

class Solution {public: int search(vector<int>& nums, int target) {  int n = nums.size(); int first = 0; int last = n - 1; int mid = first(last - first) / 2; if (nums[mid] == target)  return mid; while (first != last) {if (nums[first]<=nums[mid]) {//左侧有序if (target<nums[mid] && nums[first] <= target)last = mid - 1;elsefirst = mid1;mid = first(last - first) / 2;if (nums[mid] == target)return mid;}else if(nums[mid]<=nums[last]) {//右侧有序if (nums[mid]<target&&target <= nums[last])first = mid1;elselast = mid-1;mid = first(last - first) / 2;if (nums[mid] == target)return mid;}} return -1; }};
笔记:这道题用二分法。首先思路上要明晰:中值左右两边至少有一边是有序的,所以分为两种情形,见注释。即便如此,在测试case时还是多次出现错误结果,改的心烦意乱,还用了本地调试器帮忙。上面的答案跟许多大神的相比不够简洁,跟坨shit一样,真不知道怎么才可写出简洁准确的代码。新手起步,挫折感较强。


源文地址:https://www.guoxiongfei.cn/csdn/1491.html