二分查找

33. Search in Rotated Sorted Array 旋转数组的最小数字 剑 11 

这个题目是找给定的数字

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.

自己的代码有错。先找到最小的位置在哪,然后根据target的位置进行遍历

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int first=0,last=nums.size()-1;
        if(nums.size()==0) return -1;
        int realfirst=0,reallast=last;
        if(nums[first]>nums[last])
        {
            int maxposition=searchmin(nums)-1;
            if(nums[last]>=target)
            {
                realfirst=maxposition+1;
            }
            else 
            {
                reallast=maxposition;
            }
        }
        while(realfirst<reallast)
        {
            int middle=(realfirst+reallast)/2;
            if(target==nums[middle]) return middle;
            else if(target>nums[middle]) realfirst=middle+1;
            else if(target<nums[middle]) reallast=middle-1;
         }
        if(nums[realfirst]==target) return realfirst;
        else return -1;
        
    }
    //寻找最小的位置
    int searchmin(vector<int>&nums){
       int first=0,last=nums.size()-1;
       int middle=(first+last)/2;
        while(first<last)
        if(nums[first]>nums[last])
        {
            if(first+1==last) return last; 
            if(nums[middle]>nums[last]) first=middle;
            else if(nums[middle]<=nums[last]) last=middle;
        }
        else
           return first;
        return first;
    }
};

别人的方法:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int lo=0;
        int hi=nums.size()-1;
        if(nums.size()==0) return -1;
        while(lo<hi)
        {
            int mid=(lo+hi)/2;
            if(nums[mid]==target) return mid;
            
            if(nums[lo]<=nums[mid])//已经是递增区域.注意这里需要有等号,因为当first==last的时候,循环还是要进行的
            {
                if(target>=nums[lo]&&target<nums[mid]){ 
                    hi=mid-1;
                }
                else {
                    lo=mid+1;
                }//不在这个递增区间,转移到另一半
            }
            else//另一半一定是递增区间
            {
                if(target>nums[mid]&&target<=nums[hi])//在这个递增区间内
                {
                    lo=mid+1;
                }
                else{
                    hi=mid-1;
                }
            }
        }
        return nums[lo] == target ? lo : -1;
        
    }
};

69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

返回一个整数的平方根整数。
我的代码,出错,应该跟越界有关。一个表达式可能是越界的,需要将乘法改成除法
最开始的错误代码:
正确的代码:
class Solution {
public:
    int mySqrt(int x) {
        if(x<=0) return 0;
        if(x==1) return 1;
        //可能会越界
        long long temp=x;
        if((temp/2)<=x/(temp/2)) return temp/2;
        //这时x至少是6
        long long last=temp/2;
        long long first=last;
        while(first>x/first)
        {
            first/=2;
        }
        last=first*2;
        if(last<x/last) return last;
        return binaryxx(first,last,temp);
        
    }
    int binaryxx(long long& first,long long& last,const long long& x){
        
        while(true)
        {
        int middle=(first+last)/2;
        if(middle==x/middle||middle==first) return middle;
        if(middle>x/middle)
        {
            last=middle;
        }
        else if(middle<x/middle)
        {
            first=middle;
        }
        }
        
    }
};
其他人的思路:
思路1:二分搜索

74. Search a 2D Matrix 剑 4 二维数组查找

不同点是这里的数组首尾也是排好序的。

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

思路:把二维数组的行列坐标表示成一维即可。

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n=matrix.size();
        if(n==0) return false;
        int m=matrix[0].size();
        int begin=0,end=m*n-1;
            while(begin<=end)
            {
                int middle=(begin+end)/2;
                int temp=matrix[middle/m][middle%m];
                if(temp==target) return true;
                if(temp<target) begin=middle+1;
                else end=middle-1;
            }
        return false;
    }
};

240. Search a 2D Matrix II 剑 4 二维数组查找

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

374. Guess Number Higher or Lower

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-11, or 0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example:

n = 10, I pick 6.

Return 6.
注意溢出的情况
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        int middle;
        if(n<=1) return n;
        int first=1,last=n;
        while(first<last)
        {
           // middle=(first+last)/2; //Do NOT use (maxNumber+minNumber)/2 in case of over flow
            middle=(last-first)/2+first;
            int temp=guess(middle);
            if(temp==1)
            {
                first=middle+1;
            }
            else if(temp==-1)
            {
                last=middle-1;
            }
            else
                return middle;
        }
        return first;
    }
};

658. Find K Closest Elements

在一个数组中寻找里给定数x最近的k个数,这个x可能在数组中也可能不在。如果满足多种可能,找到尽量小的那种排列。这里的最近指的是数值大小相近而不是下标距离
自己尝试后,发现问题不是那么简单呀。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值