1. 程式人生 > >LeetCode數組類的題目提交記錄 【2】

LeetCode數組類的題目提交記錄 【2】

targe result 有序 suppose middle size body some 遞歸

/***********************************************************************
33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order 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.


eg:

0 1 2 3 4//右邊有序情況
4 0 1 2 3//右邊有序情況
3 4 0 1 2//右邊有序情況

2 3 4 0 1//左邊有序情況
1 2 3 4 0//左邊有序情況
**************************************************************/

//代碼提交1

//循環法---查找
int search(int* nums, int numsSize, int target) {
    int Left= 0;
    int Right = numsSize - 1
; int Middle; while (Left <= Right) { Middle = (Left + Right) / 2; if (target == *(nums + Middle)) { return Middle; } if (*(nums + Middle) < *(nums + Right)) {//右邊有序情況 //1.把目標在限制死在中間值的 右邊 if (*(nums + Middle) < target && *(nums + Right) >= target) Left
= Middle + 1; //2.其他情況則目標在中間值的 左邊 else Right = Middle - 1; continue; } if (*(nums + Middle) > *(nums + Right)) {//左邊有序情況 //1.把目標限制死在中間值的 左邊 if (*(nums + Middle) > target && *(nums + Right) < target) Right = Middle - 1; //2.其他情況則目標在中間值的 右邊 else Left = Middle + 1; continue; } return -1; } return -1; }

  

//代碼提交2
//遞歸法---查找
int searchFun(int* nums, int nLeft,int nRight,int ntargrt) {
    int Left = nLeft;
    int Right = nRight;
    int Middle = (Left + Right) / 2;

    if (Left <= Right)
    {
        if (*(nums + Middle) == ntargrt) {
            return Middle;
        }

        if (*(nums + Middle) < *(nums + Right))
        {
            if (*(nums + Middle) < ntargrt && ntargrt <= *(nums + Right)) 
            {
                Left = Middle + 1;
                return searchFun(nums,Left,Right,ntargrt);
            }
            else            
            {
                Right = Middle - 1;
                return searchFun(nums, Left, Right, ntargrt);
            }
        }

        if (*(nums + Middle) > *(nums + Right)) 
        {
            if (*(nums + Middle) > ntargrt && ntargrt > *(nums + Right))
            {
                Right = Middle - 1;
                return searchFun(nums, Left, Right, ntargrt);
            }
            else 
            {
                Left = Middle + 1;
                return searchFun(nums, Left, Right, ntargrt);
            }
        }

        return -1;
    }

    return -1;
}
int search(int* nums, int numsSize, int target) {
    int Left = 0;
    int Right = numsSize - 1;

    int resultNum = searchFun(nums,Left,Right,target);
    return resultNum;
}

  

LeetCode數組類的題目提交記錄 【2】