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;
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章