LeetCode 380. Insert Delete GetRandom O1

Design a data structure that supports all following operations in average O(1) time.

insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

继续阅读
LeetCode 376. Wiggle Subsequence

LeetCode 376. Wiggle Subsequence

Description
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

继续阅读
LeetCode 375. Guess Number Higher or Lower II

LeetCode 375. Guess Number Higher or Lower II

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 I picked is higher or lower.

However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

Example:

n = 10, I pick 8.

First round: You guess 5, I tell you that it’s higher. You pay 5. Second round: You guess 7, I tell you that it’s higher. You pay5.Secondround:Youguess7,Itellyouthatit

shigher.Youpay7.
Third round: You guess 9, I tell you that it’s lower. You pay $9.

Game over. 8 is the number I picked.

You end up paying 5 +5+7 + 9 =9=21.
Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.

继续阅读
LeetCode 374. Guess Number Higher or Lower

LeetCode 374. Guess Number Higher or Lower

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.

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 :

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

继续阅读