程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetCode 33.Search in Rotated Sorted Array(排序旋轉數組的查找) 解題思路和方法

leetCode 33.Search in Rotated Sorted Array(排序旋轉數組的查找) 解題思路和方法

編輯:C++入門知識

leetCode 33.Search in Rotated Sorted Array(排序旋轉數組的查找) 解題思路和方法


Search in Rotated Sorted Array

 

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

 

思路:此題算法上不難,第一步計算旋轉的步長。然後根據步長分情況得到升序的新的數組。然後二分查找target的索引,找到後再分情況返回元素的位置。

具體代碼如下:

 

public class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0){
            return -1;
        }
        
        if(nums.length == 1){
            if(nums[0] == target)
                return 0;
            return -1;
        }
        
        int rotate = 0;//旋轉的步長
        for(int i = nums.length - 1; i > 0; i--){
            if(nums[i] < nums[i-1]){
                rotate = i;
                break;
            }
        }
        int[] a = new int[nums.length];
        //將數組按升序填充到新數組
        for(int i = rotate; i < nums.length; i++){
            a[i - rotate] = nums[i];//後面未旋轉部分
        }
        for(int i = 0; i < rotate; i++){
            a[i+nums.length-rotate] = nums[i];//前面旋轉部分
        }
        
        int index = -1;
        //二分查找
        int low = 0;
        int hight = nums.length - 1;
        while(low <= hight){
            int mid = (low + hight)/2;
            if(a[mid] > target){
                hight = mid - 1;
            }else if(a[mid] == target){
                index = mid;
                break;
            }else{
                low = mid + 1;
            }
        }
        if(index == -1)
            return -1;
        if(index + rotate > nums.length - 1)
            return index + rotate - nums.length;
        return index + rotate;
    }
}


 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved