您的位置:首页 > 职场人生

面试笔试杂项积累-leetcode 291-300

2016-02-13 23:22 567 查看

292.292-Nim Game-Difficulty: Easy

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.

Hint:

If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

思路

根据hint提示,首先想到剩下4个对方先拿怎样都能赢,然后想到,在自己先拿的情况下

1-3//5-7//9-11..都能稳赢,所以4的倍数不能拿到

public class Solution {
public bool CanWinNim(int n) {
if (n % 4 == 0)
return false;
return true;
}
}


300.300-Longest Increasing Subsequence-Difficulty: Medium

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,

Given
[10, 9, 2, 5, 3, 7, 101, 18]
,

The longest increasing subsequence is
[2, 3, 7, 101]
, therefore the length is
4
. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

思路
最长的连续递增数的数目

动态规划

public class Solution {
public int LengthOfLIS(int[] nums) {
if (nums.Length <= 0)
return 0;
int[] DP = new int[nums.Length];
DP[0] = 1;
int max = 1;
for (int i = 1; i < nums.Length; i++)
{
DP[i] = 1;
for (int j = 0; j < i; j++)
{
if (nums[i] > nums[j])//等于不算
{
// ++DP[j];
DP[i] =Math.Max(DP[i], DP[j]+1);
}
}
max = Math.Max(DP[i], max);
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: