LeetCode 374. Guess Number Higher or Lower

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.

分析:二分查找法解决,不过要注意mid = low + (high – low) / 2 不要写成 mid = (low + high) / 2 ,后者超过了Int类型的最大值,相加变成负数,会导致超时~~

 

LeetCode 396. Rotate Function

Given an array of integers A and let n to be its length.

Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a “rotation function” F on A as follow:

F(k) = 0 * Bk[0] + 1 * Bk[1] + … + (n-1) * Bk[n-1].

Calculate the maximum value of F(0), F(1), …, F(n-1).

Note:
n is guaranteed to be less than 105.

Example:

A = [4, 3, 2, 6]

F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26

So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

分析:算出每个F[i],求出最大值maxn~每个F[i]可由前一步F[i-1]得到,F[i] = F[i – 1] + sum – len * A[len – i],其中sum为A[i]总和,len为A[i]长度~找到这个关系后就能求得F[i]的所有值~

 

LeetCode 401. Binary Watch

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).

Each LED represents a zero or one, with the least significant bit on the right.

For example, the above binary watch reads “3:25”.

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

Example:

Input: n = 1
Return: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]

分析:小时数h从0~11,分钟数m从0~59,把他们每一个转换为一个二进制整体,初始化为bitset,看bitset中1的个数是否为num,如果是就将h和m构成一个字符串加入到result字符串数组中,最后返回result~~

 

【C++】bitset的用法

bitset用来处理二进制位非常方便。头文件是#include <bitset>,在std命名空间里面~

 

LeetCode 151. Reverse Words in a String

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

分析:我用的方法是把字符串中的所有单词放入栈里,然后将栈里的所有字符串弹栈到字符串s中~

 

LeetCode 350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.

分析:将nums1的每一个数字以及对应数字的个数存储在map里面,遍历nums2中的所有元素,如果当前元素在map中存在,就把它放入result数组中,并将其数量-1。最终返回result即为所求交集~