1. 程式人生 > >【LeetCode】#81搜尋旋轉排序陣列 II(Search in Rotated Sorted Array II)

【LeetCode】#81搜尋旋轉排序陣列 II(Search in Rotated Sorted Array II)

【LeetCode】#81搜尋旋轉排序陣列 II(Search in Rotated Sorted Array II)

題目描述

假設按照升序排序的陣列在預先未知的某個點上進行了旋轉。
( 例如,陣列 [0,0,1,2,2,5,6] 可能變為 [2,5,6,0,0,1,2] )。
編寫一個函式來判斷給定的目標值是否存在於陣列中。若存在返回 true,否則返回 false。

示例

示例 1:

輸入: nums = [2,5,6,0,0,1,2], target = 0
輸出: true

示例 2:

輸入: nums = [2,5,6,0,0,1,2], target = 3
輸出: false

Description

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.

Example

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

解法

class Solution {
    public boolean search(int[] nums, int target) {
        int f = 0, l = nums.length-1;
        while(f<=l){
            if(nums[f]==target || nums[l]==target)
                return true;
            f++;
            l--;
        }
        return false;
    }
}