<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">从今天开始撸LeetCode。嗯,AC率从高到低来刷。</span>
344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
public class Solution {
public static String reverseString(String s) {
if(s.length()==0) return "";
char[] sCopy = new char[s.length()];
for(int i=0; i< s.length()/2+1; i++){
sCopy[i]=s.charAt(s.length()-i-1);
sCopy[s.length()-i-1]=s.charAt(i);
}
return new String(sCopy);
}
public static void main(String[] args) {
System.out.println(reverseString(""));
}
}
292. Counting Bits
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
public class Solution {
public int[] countBits(int num) {
int twom=0;
int[] count = new int[num+1];
int twolast1=0;
int twolast2=(int)Math.pow(2, twom+1)-1;
//当前左右区间
count[0]=0;
for(int i=1;i<=num;i++){
if(i==1) count[1]=1;
else if(i>twolast1 && i<=twolast2)
{
count[i] = count[twolast1]+count[i-twolast1];
}else{
count[i]=1;
twom++;
twolast1=(int)Math.pow(2, twom);
twolast2=(int)Math.pow(2, twom+1)-1;
}
}
return count;
}
}
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.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------public class Solution {
public static boolean canWinNim(int n) {
boolean[] IFirst = new boolean[n+1];
IFirst[1]=true;
if (n==1) return IFirst[1];
IFirst[2]=true;
if (n==2) return IFirst[2];
IFirst[3]=true;
if(n==3) return IFirst[3];
for(int i=4;i<=n;i++){
int failnum=0;
for(int j=1;j<=3;j++){
//如果此时我先选择,剩下来的数目使得你有获胜的机会
if(IFirst[i-j]){
failnum++;
}
}
//如果不论怎样选择,你都会获胜
if(failnum==3){
IFirst[i] = false;
}else{
IFirst[i]=true;
}
}
return IFirst[n];
}
}
这个结果是没什么问题的。然后Submit,内存超了。。。
public class Solution {
public boolean canWinNim(int n) {
return n%4==0? false:true;
}
}
为什么?自己想。。。