赞
踩
递归是常见的一种解题策略,但缺点是递归层数太深的话会浪费巨大的时间空间,还会造成多次运算的情况出现。如下题。
f(0)=0,
f(1)=1,
f(n)=f(n-1)+f(n-2)
类似这种题,在n比较大时,底层的数会重复加很多次(如f(4)本来只需算一次,但递归下可能每次遇到f(4)都得再算一遍),这样就浪费了大量的时间。
优化:
public static int fib2(int n) {
int a = 0, b = 1, sum;
for(int i = 0; i < n; i++){
sum = a + b;
a = b;
b = sum;
}
return a;
}
题目:
输入: s = "abcdefg", k = 2 输出: "cdefgab"
输入: s = "lrloseumgh", k = 6 输出: "umghlrlose"
//我的解法 class Solution { public String reverseLeftWords(String s, int n) { char[] ss =s.toCharArray(); String news=""; for (int i = n; i <s.length() ; i++) { news=news+ss[i]; } for (int i = 0; i < n; i++) { news=news+ss[i]; } return news; } } //改进版 class Solution { public String reverseLeftWords(String s, int n) { char[] ss =s.toCharArray(); StringBuilder news=new StringBuilder(); for (int i = n; i <s.length() ; i++) { news.append(ss[i]); } for (int i = 0; i < n; i++) { news.append(ss[i]); } return news.toString(); } }
//100% ,55%
class Solution {
public String reverseLeftWords(String s, int n) {
return s.substring(n, s.length()) + s.substring(0, n);
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head,
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。