刷题思路来源于 代码随想录
class Solution {
public int search(int[] nums, int target) {
if(nums.length==0||nums==null){
return -1;
}
int left=0;
int right=nums.length-1;
while(left<=right){
int middle=left+(right-left)/2;
if(nums[middle]<target){
left=middle+1;
}else if(nums[middle]>target){
right=middle-1;
}else{
return middle;
}
}
return -1;
}
}
class Solution {
public int search(int[] nums, int target) {
if(nums.length==0||nums==null){
return -1;
}
int left=0;
int right=nums.length;
while(left<right){
int middle=left+(right-left)/2;
if(nums[middle]>target){
right=middle;
}else if(nums[middle]<target){
left=middle+1;
}else{
return middle;
}
}
return -1;
}
}
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length==0||nums==null){
return -1;
}
int n=nums.length;
if(target<nums[0]){
return 0;
}
if(target>nums[n-1]){
return n;
}
int left=0;
int right=n-1;
while(left<=right){
int middle=left+(right-left)/2;
if(nums[middle]<target){
left=middle+1;
}else if(nums[middle]>target){
right=middle-1;
}else{
return middle;
}
}
// 其实这个也可以
// return left;
return right+1;
}
}
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums==null||nums.length==0){
return new int[]{-1,-1};
}
if(target<nums[0]||target>nums[nums.length-1]){
return new int[]{-1,-1};
}
int left=findLeft(nums,target);
int right=findRight(nums,target);
if(left==-2||right==-2){
return new int[]{-1,-1};
}
return new int[]{left+1,right-1};
}
private int findLeft(int[] nums, int target){
int result=-2;
int left=0;
int right=nums.length-1;
while(left<=right){
int middle=left+(right-left)/2;
if(nums[middle]>target){
right=middle-1;
}else if(nums[middle]<target){
left=middle+1;
}else{
right=middle-1;
result=right;
}
}
return result;
}
private int findRight(int[] nums, int target){
int result=-2;
int left=0;
int right=nums.length-1;
while(left<=right){
int middle=left+(right-left)/2;
if(nums[middle]<target){
left=middle+1;
}else if(nums[middle]>target){
right=middle-1;
}else{
left=middle+1;
result=left;
}
}
return result;
}
}
class Solution {
public int mySqrt(int x) {
if(x==0||x==1){
return x;
}
int left =0;
int right=x/2+1;
while(left<=right){
int middle=left+(right-left)/2;
long result=(long)middle*middle;
if(result>x){
right=middle-1;
}else if(result<x){
left=middle+1;
}else{
return middle;
}
}
return right;
}
}
class Solution {
public boolean isPerfectSquare(int num) {
if(num==0||num==1){
return true;
}
int left=1;
int right=num/2+1;
while(left<=right){
int middle=left+(right-left)/2;
long result=(long)middle*middle;
if(result<num){
left=middle+1;
}else if(result>num){
right=middle-1;
}else{
return true;
}
}
return false;
}
}