38.报数
自己思路:每一个字符串都由上一个字符串得出,想到了用递归的方法,代码如下:
class Solution {
public String countAndSay(int n) {
String s = getS(n);
return s;
}
public static String getS(int n){
if(n == 1) //如果 n 为1,直接返回"1"
return "1";
else{
String s1 = getS(n - 1); //递归调用
int count = 1; //初始化
String s = "";
int pre = s1.charAt(0) - 48;
for(int i = 1 ; i < s1.length() ; i++){
if(pre == s1.charAt(i) - 48){
count++;
}else{
s = s + count + pre;
pre = s1.charAt(i) - 48;
count = 1;
}
}
s = s + count + pre;
return s;
}
}
}
运行之后可以通过,但是时间过长,看了别人的代码发现可以直接用循环解决。并且用StringBuilder类可以比用String类显著的缩短运行时间 。代码如下:
class Solution {
public String countAndSay(int n) {
StringBuilder ans = new StringBuilder();
ans.append("1");
for(int i = 2 ; i <= n ; i++){
//遍历上一个字符串
String s = new String(ans); //用s接收上一个字符串
ans.delete(0 , ans.length());//清空ans
int count = 0;
char pre = s.charAt(0);
for(char c : s.toCharArray()){
if(pre == c){
count++;
}else{
ans.append(count);
ans.append(pre);
pre = c;
count = 1;
}
}
ans.append(count);
ans.append(pre);
}
return ans.toString();
}
}
509.斐波那契数
自己思路:利用简单的递归即可,但是时间太长。更快的方法是用循环。
class Solution {
public int fib(int N) {
if(N == 0)
return 0;
if(N == 1)
return 1;
else{
return fib(N-1) + fib(N-2);
}
}
}
1122.数组的相对排序
解题思路:这道题利用了桶排序,先用一个桶存储arr1中的元素,再利用arr2将其取出,然后把桶中的元素按顺序取出来。
class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
int[] bucket = new int[1001];
for(int i = 0 ; i < arr1.length ; i++){
bucket[arr1[i]]++;
}
int idx = 0;
for(int i = 0 ; i < arr2.length ; i++){
while(bucket[arr2[i]] > 0){
bucket[arr2[i]]--;
arr1[idx++] = arr2[i];
}
}
for(int i = 0 ; i < bucket.length ; i++){
while(bucket[i] > 0){
bucket[i]--;
arr1[idx++] = i;
}
}
return arr1;
}
}