Leetcode 二分查找

69. Sqrt(x)
Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2
JAVA

class Solution {
    public int mySqrt(int x) {
        int left=1,right=x;
        while(left<=right)
        {
            int mid=left+(right-left)/2;
            if(x/mid==mid)
                return mid;
            else if(x/mid>mid)
                left=mid+1;
            else
                right=mid-1;
        }
        return right;
    
    }
}

704. Binary Search
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
JAVA

class Solution {
    public int search(int[] nums, int target) {
      int left=0,right=nums.length;
      while(left<right)
      {
          int mid=left+(right-left)/2;
          if(nums[mid]==target)
            {
              return mid;
             }
          else if(nums[mid]<target)
              left+=1;
          else
              right-=1;
      }
        return -1;
    }
   
}

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.

Your algorithm’s runtime complexity must be in the order of O(log n).

Example 1:

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

class Solution {
public int search(int [] nums,int target)
{
	int left=0,right=nums.length-1;
	while(left<=right)
	{
	  int mid=left+(right-left)/2;
	  if(nums[mid]==target)
	  return mid;
	  if(nums[mid]<nums[right])
	  {
	    if(nums[mid]<target && target <=nums[right])
	      left=mid+1;
	    else
	      right=mid-1;
	  }
	  else
	  {
	    if(nums[mid] > target && target >= nums[left])
	     right=mid-1;
	    else
	      left=mid+1;
	  }
	}
	return -1;
  }
}

81. Search in Rotated Sorted Array II
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 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
和上一道题很相似
当 nums[mid] = nums[right] 时,这时由于很难判断 target 会落在哪,那么只能采取 right–

当 nums[mid] <nums[right] 时,这时可以分为两种情况,判断右半部比较简单

当 nums[mid] > nums[right] 时,这时可以分为两种情况,判断左半部比较简单

class Solution {
    public boolean search(int[] nums, int target) {
        int left=0,right=nums.length-1;
	while(left<=right)
	{
	  int mid=left+(right-left)/2;
	  if(nums[mid]==target) return true;
	  if(nums[mid]==nums[right]) right--;
	  else if(nums[mid] < nums[right])
	  {    
          if(nums[mid]<target && target <=nums[right])
	        left=mid+1;
	      else
	      right=mid-1;
	  }
	  else 
	  { 
          if(nums[mid] > target && target >= nums[left])
	         right=mid-1;
	      else
	         left=mid+1; 
	  }
	}
	return false;
    }
}

153. Find Minimum 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]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

Input: [3,4,5,1,2]
Output: 1
Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0
给定一旋转有序数组,求该数组的最小值。
binary search. O(logn)
(1) A[mid] < A[end]:A[mid : end] sorted => min不在A[mid+1 : end]中
搜索A[start : mid]
(2) A[mid] > A[end]:A[start : mid] sorted且又因为该情况下A[end]<A[start] => min不在A[start : mid]中
搜索A[mid+1 : end]

class Solution {
    public int findMin(int[] nums) {
        int left=0,right=nums.length-1;
        while(left<right)
        {
            int mid=left+(right-left)/2;
            if(nums[mid]<nums[right])
                right=mid;
            else
                left=mid+1;
        }
         return nums[left];
    }
   
}

162. Find Peak Element
A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums[-1] = nums[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
题目:给定一个整型数组,从中找出某一个元素,使得该元素比其左右元素都大,求该元素在数组中的位置
题目中已经说明,最左端和最右端元素均无限小,中间元素比两侧都要大,那么本题中一定存在一个峰元素。所以不管中间有多少波峰,只要找到峰元素,我们只需找到刚刚开始下降而未下降的位置。采用二分查找,查出这样一个位置即可,我们知道二分查找要比较的是 target 元素,本题的 target 元素是 mid 的后一个元素,即 nums[mid] 与 nums[mid+1] 进行比较

class Solution {
    public int findPeakElement(int[] nums) {
        int left=0,right=nums.length-1;
        while(left<right)
        { 
            int mid=left+(right-left)/2;
            if(nums[mid]<nums[mid+1]) left=mid+1;
            else right=mid;
        }
        return left;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值