二分查找

14.二分查找

百度了一下vector的使用方法,利用《数据结构》P192的二分查找

class Solution {
public:
    /**
     * @param nums: The integer array.
     * @param target: Target number to find.
     * @return: The first position of target. Position starts from 0. 
     */
    int binarySearch(vector<int> &array, int target) {
        // write your code here
        int low =0,high=array.size()-1,mid;
        
        while(low<=high)
        {
            mid = (low+high)/2;
            if(target<array[mid])
                high = mid-1;
            if(target>array[mid])
                low = mid+1;
            if(target == array[mid])
            {
                 while(target == array[mid-1])
                    {
                        mid = mid-1;
                    }
                return mid;
            }
        }
        return -1;
    }
};

9.Fizz Buzz 问题

 

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string>v;
        for (int i = 1; i <= n; i++){
            string s;
            if (i % 3 == 0){
                s = "fizz";
                if (i % 5 == 0){
                    s = s + " buzz";
                }
            }
            else if (i % 5 == 0) {
                s = "buzz";
            }
            else {
                s = to_string(i);
            }
            v.push_back(s);
        }
        return v;
    }
};

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值