[LeetCode]374. Guess Number Higher or Lower ★

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/xingyu97/article/details/100590544

Title Description

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.

Call A pre-defined by You the API GUESS (int NUM) Which Returns. 3 Possible Results (-1,. 1, or 0):
-1: My Number Lower IS
. 1: My Number IS IN AREAS OF COMMUNICAITIONS
0:!! Congrats by You GOT IT
subject to the effect : select a number between [1, n], and then write the program to guess which number is selected, a given API guess, guess return to step number 1 indicates a small, -1 represents large numbers guess, 0 indicates guess.

Sample

Example :

Input: n = 10, pick = 6
Output: 6

python Solution

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):

class Solution(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        l, r = 1, n
        while True:
            global g
            mid = l + (r-l)/2
            g = guess(mid)
            if g == 0:
                return mid
            elif g > 0:
                l = mid + 1
            else:
                r = mid - 1
        return -1

When executed with: 20 ms
memory consumption: 11.7 MB

Title after reflection:

C ++ Language Solution

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
        int mid, l =1, r = n, g;
        while(true)
        {
            mid = l + (r - l)/2;
            g = guess(mid);
            if (g == 0)
            {
                break;
            }
            else if (g > 0)
            {
                l = mid + 1;
            }
            else 
            {
                r = mid - 1;
            }
        }
        return mid;
    }
};

When executed with: 4 ms
memory consumption: 8.1 MB

Title after reflection:

  1. Two intermediate value by the number of adding two numbers may be divided by 2, but in a computer to prevent exceeding int type data may represent a range of integers, the value by using the left half of the number of median formation of two distances.

This paper is my personal understanding, if the wrong place welcome comments below tell me, I promptly corrected, common progress

Guess you like

Origin blog.csdn.net/xingyu97/article/details/100590544