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;
}
};