leecode 解题总结:374. Guess Number Higher or Lower

来源:互联网 发布:tensorflow vgg 微调 编辑:程序博客网 时间:2024/06/17 16:14
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题: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 (-1, 1, 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.分析:实际上就是猜数字游戏。给定n,求猜别人拿的是哪个数字。一种方式是用二分法:*/int guess(int num);class Solution {public:    int guessNumber(int n) {int high = n;        int low = 1;int mid;while(low < high){mid = low + (high - low) / 2;int guessValue = guess(mid);//实际数值小于midif(-1 == guessValue){high = mid - 1;}else if(1 == guessValue){low = mid + 1;}else{return mid;}}return low;    }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0