LeetCode 33. Search rotation sorted array (C # implementation) - binary search

Question: https://leetcode-cn.com/problems/search-in-rotated-sorted-array/submissions/

Suppose ascending order according to the array was rotated in a previously unknown point. 

(E.g., array [ 0 , 1 , 2 , 4 , 5 , 6 , 7 ] may become [ 4 , 5 , 6 , 7 , 0 , 1 , 2 ]). 

Searching for a given target value, if the existence of the target array, its index returns, otherwise it returns - 1 . 

You can assume that the array element does not exist in duplicate. 

Your time complexity of the algorithm must be O (log n) level. 

Example 1 : 

Input: the nums = [ . 4 , . 5 , . 6 , . 7 , 0 ,. 1 , 2 ], target = 0 
Output: 4 

Example 2 : 

Input: the nums = [ 4 , . 5 , . 6 , . 7 , 0 , . 1 , 2 ], target = . 3 
Output: - . 1

GitHub realization: https://github.com/JonathanZxxxx/LeetCode/blob/master/Class33.cs

Thinking: binary search, with left and right portions of the logic to determine

        public int Search(int[] nums, int target)
        {
            int start = 0;
            int end = nums.Length - 1;
            while (start <= end)
            {
                int mid = (start + end) / 2;
                if (nums[mid] == target) return mid;
                //左半边有序
                if (nums[start] <= nums[mid])
                {
                    //target在这段里
                    if (nums[start] <= target && target < nums[mid])
                    {
                        end = mid - 1;
                    }
                    else
                    {
                        start = mid + 1;
                    }
                }
                else
                {
                    if (nums[mid] < target && target <= nums[end])
                    {
                        start = mid + 1;
                    }
                    else
                    {
                        end = mid - 1;
                    }
                }
            }
            return -1;
        }

 

Guess you like

Origin www.cnblogs.com/zxxxx/p/11725475.html