按难度排序,每天刷点leetcode题,抄点解法,大部分解答是在leetcode的dicuss中找到的,没有一一引用,抱歉。
292 Nim Game
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
Ans:当石子是4的整数倍时,无法赢。
371 Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Ans:
// Recursive
public int getSum(int a, int b) { return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);}
258Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:Could you do it without any loop/recursion in O(1) runtime?
Ans:
class Solution {
public:
int addDigits(int num) {
return (num-1)%9 + 1;
}
};
104Maximum Depth of Binary Tree&226Invert Binary Tree
Ans:二叉树的简单操作
283 Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.For example,given nums = [0, 1, 0, 3, 12], after calling your function, nums
should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Ans:
class Solution {
public: void moveZeroes(vector<int>& nums)
{ int j = 0; // move all the nonzero elements advance for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { nums[j++] = nums[i]; } } for (;j < nums.size(); j++) { nums[j] = 0; } }};
网友评论