LeetCode - Algorithms - 121. Best Time to Buy and Sell Stock

虽然难度标为Easy,但自己居然提交了好几次才通过了,而且是因为犯了逻辑错误。最后用个二重循环,倒也简单,但性能不好,不知道高效算法是如何做的?

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int maxProfit(int[] prices) {
if (prices==null || prices.length==0)
return 0;
int r = 0;
for(int i=0;i<prices.length-1;i++) {
for(int j=prices.length-1;j>i;j--) {
if (prices[j]-prices[i]>r) {
r = prices[j]-prices[i];
}
}
}
return r;
}
}

Submission Detail

  • 200 / 200 test cases passed.
  • Your runtime beats 4.30 % of java submissions.

在网上人家的一个O(n)时间复杂度的算法

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int maxProfit(int[] prices) {
if (prices==null || prices.length<=1)
return 0;
int r = 0;
int minPrice = prices[0];
for(int i=1;i<prices.length;i++) {
r = Math.max(r, prices[i]-minPrice);
minPrice = Math.min(minPrice, prices[i]);
}
return r;
}
}

Submission Detail

  • 200 / 200 test cases passed.
  • Your runtime beats 32.88 % of java submissions.

JavaScript

O(n2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
if (prices==null || prices.length==0)
return 0;
var r=0;
var x = 0;
for(var i=0;i<prices.length-1;i++) {
for(var j=prices.length-1;j>i;j--) {
x = prices[j]-prices[i];
if (x>r)
r = x;
}
}
return r;
};

Submission Detail

  • 200 / 200 test cases passed.
  • Your runtime beats 7.71 % of javascript submissions.

O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
if (prices==null || prices.length<=1)
return 0;
var r=0;
var minPrice = prices[0];
for(var i=1;i<prices.length;i++) {
r = Math.max(r,prices[i]-minPrice);
minPrice = Math.min(minPrice,prices[i]);
}
return r;
};

Submission Detail

  • 200 / 200 test cases passed.
  • Your runtime beats 84.89 % of javascript submissions.

英语学习相关网站

听力

Voice of America - Learn American English with VOA Learning English
https://learningenglish.voanews.com/

BBC Learning English | Pronunciation Tips
http://www.bbc.co.uk/worldservice/learningenglish/grammar/pron/

60-Second Science
https://www.scientificamerican.com/podcast/60-second-science/

Videos & Podcasts - Scientific American
https://www.scientificamerican.com/multimedia/

TED Radio Hour
https://www.npr.org/programs/ted-radio-hour

BBC - World Service - Home
https://www.bbc.co.uk/worldserviceradio

Learning English - 6 Minute English
http://www.bbc.co.uk/worldservice/learningenglish/general/sixminute/

词典

Dictionary by Merriam-Webster: America’s most-trusted online dictionary
https://www.merriam-webster.com/

Collins Dictionary
https://www.collinsdictionary.com/

Dictionary.com
https://www.dictionary.com/

报刊

https://medium.com/

https://www.theatlantic.com/

https://www.newyorker.com/

https://www.npr.org/

https://www.economist.com/

https://www.bloomberg.com/businessweek

https://www.bloomberg.com/canada

https://www.theguardian.com/observer

https://www.theguardian.com/international

http://www.bbc.com/

https://www.telegraph.co.uk/

其他

A Free Online Talking Dictionary of English Pronunciation
https://www.howjsay.com/

UsingEnglish.com was established in 2002 and is a general English language site specialising in English as a Second Language (ESL).
https://www.usingenglish.com/

Discovery Canada
https://www.discovery.ca/Home

English Language & Usage Stack Exchange is a question and answer site for linguists, etymologists, and serious English language enthusiasts.
https://english.stackexchange.com/

LeetCode - Algorithms - 119. Pascal's Triangle II

118. Pascal’s Triangle 的变脸题,用递归的方式实现了,还没想通如何用动态规划的方式实现。

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
if (rowIndex==0) {
list.add(1);
return list;
}
if (rowIndex==1) {
list.add(1);
list.add(1);
return list;
}
if (rowIndex>=2) {
List<Integer> row_pre = getRow(rowIndex-1);
list.add(1);
for(int i=1;i<rowIndex;i++) {
list.add(row_pre.get(i)+row_pre.get(i-1));
}
list.add(1);
}
return list;
}
}

Submission Detail

  • 34 / 34 test cases passed.
  • Your runtime beats 89.30 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {number} rowIndex
* @return {number[]}
*/
var getRow = function(rowIndex) {
if (rowIndex==0) {
return [1];
}
if (rowIndex==1) {
return [1,1];
}
var arr = [];
if (rowIndex>=2) {
arr.push(1);
var preRow = getRow(rowIndex-1);
for(var i=1;i<rowIndex;i++)
arr.push(preRow[i]+preRow[i-1]);
arr.push(1);
}
return arr;
};

Submission Detail

  • 34 / 34 test cases passed.
  • Your runtime beats 93.58 % of javascript submissions.

LeetCode - Algorithms - 118. Pascal's Triangle

不难,不过写递归过程还是犯了些错误。 Pascal’s triangle 挺有名的,Binomial Coefficients好像是很重要的组合数学概念。

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<List<Integer>>();

if (numRows==1) {
List<Integer> list0 = new ArrayList<Integer>();
list0.add(1);
list.add(list0);
return list;
}

if (numRows==2) {
List<Integer> list0 = new ArrayList<Integer>();
list0.add(1);
list.add(list0);
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(1);
list.add(list1);
return list;
}

if (numRows>=3) {
List<List<Integer>> list_= generate(numRows-1);
List<Integer> list_pre = list_.get(numRows-2);
for(int i=0;i<list_.size();i++)
list.add(list_.get(i));
List<Integer> list_curr = new ArrayList<Integer>();
list_curr.add(1);
for(int i=1;i<numRows-1;i++) {
list_curr.add(list_pre.get(i)+list_pre.get(i-1));
}
list_curr.add(1);
list.add(list_curr);
}
return list;
}

Submission Detail

  • 15 / 15 test cases passed.
  • Your runtime beats 100.00 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
if (numRows==1) {
return [[1]];
}
if (numRows==2) {
return [[1],[1,1]];
}
var arr = [];
if (numRows>=3) {
var arr_ = generate(numRows-1);
var line_pre = arr_[numRows-2];
for(i=0;i<arr_.length;i++)
arr.push(arr_[i]);
var line_curr = [1];
for(i=1;i<numRows-1;i++) {
line_curr.push(line_pre[i]+line_pre[i-1]);
}
line_curr.push(1);
arr.push(line_curr);
}
return arr;
};

Submission Detail

  • 15 / 15 test cases passed.
  • Your runtime beats 90.59 % of javascript submissions.

Better than the Four Colour Theorem - Jim Geelen - mathNEWS - VOLUME 135 • ISSUE 3 - October 20, 2017

There is a limpid mathematics journal at the University of Waterloo named mathNEWS, this essay was selected from that little journal. University of Waterloo’s campus has a street named William Tutte way near Davis Centre Library.


William Tutte spent enormous effort trying to solve the Four Colour Problem. Even after the computer-aided proof of Appel and Haken in 1976, Tutte continued working toward finding a short, human-readable, proof.

Tutte never did succeed, but he came close to achieving his goal on several occasions. For example, Tutte had significant insights into Tait’s Conjecture that three-connected cubic planar graphs are Hamiltonia n, which Tait had already shown to imply the Four Colour Conjecture. Unfortunately, instead of leading him to a proof, Tutte’s insights led him to discover a 46-vertex counter-example to Tait’s conjecture. Not long after that, Tutte proved that all four-connected planar graphs are Hamiltonian. While this is agonizingly close to Tait’s Conjecture, it does not have any immediate applications to colouring.

Tutte graph

Following those attempts, Tutte tried various algebraic approaches; one of these involved the chromatic polynomial of a graph. For a graph G and non-negative integer k, let \( \lambda_G(k) \) denote the number of colourings of G with colours 1, …, k. It is not at all obvious from this definition, but \( \lambda_G \) is a polynomial, which allows us to define it at values other than the positive integers.

The Four Colour Conjecture states that \( \lambda_G(4) > 0 \) whenever G is planar. If \( 0 \leq k_1 \leq k_2 \) are integers, then any \( k_1 \)-colouring is a \( k_2 \)-colouring, and hence \( \lambda_G(k_2) \geq \lambda_G(k_1) \). This property does not extend to non-negative real numbers, but it is conjectured that for each real number \( x \geq 4 \), we have \( \lambda_G(x) > 0 \) whenever G is planar. Tutte proved the following amazing result which superficially looks stronger than the Four Colour Theorem; in this result \( \tau \) is the golden ratio, so \( \tau+2=\frac{5+\sqrt{5}}{2} \approx 3.618 \).

The 3.618 Colour Theorem. For each planar graph G, we have
\( \lambda_G(\tau+2) > 0 \).

This year Gordon Royle proved that, if \( x < 4 \) is a real number such that \( \lambda_G(x) > 0 \) for each planar graph G, then \( x = \tau+2 \). Wow!

How on earth, you may ask, did Tutte come upon his result? It turns out that he came across the idea to try \( \tau+2 \) by empirical evidence. That evidence takes the form of eight large binders that are stored in the C&O library on the sixth floor of the MC building. Each of these binders contains, at a guess, around 500 pages. The pages alternate between a beautiful hand-drawn picture of a planar graph and a computer print out of the roots of its chromatic polynomial. Tutte enlisted the help of Ruth Bari and Dick Wick Hall to systematically generate the graphs and the help of Gerry Berman, founder of the C&O Department, to compute the chromatic roots. Nevertheless, it beggars belief to consider the work that Tutte put into drawing each of the graphs by hand and then trawling through these volumes for any patterns that might provide in-roads to the elusive Four Colour Conjecture. In the end he made do with only 3.618 colours.

This article is in memory of William T. Tutte, in this the centennial year of his birth. Among other honours, Tutte was a founding member of the C&O Department, a legendary World War II code breaker, and a hugely influential combinatorialist.

Jim Geelen


  • One of the most prolific graph theorists, William T. Tutte, judged the impact of the four-color theorem on mathematics by proclaiming: “The four-colour theorem is the tip of the iceberg, the thin end of the wedge, and the first cuckoo of Spring.” (The Princeton Companion to Mathematics - Part V Theorems and Problems - V.12 The Four-Color Theorem, by Bojan Mohar)
  • The Colorful Problem That Has Long Frustrated Mathematicians
  • I imagine one of them outgribing in despair, crying ‘What shall I do now?’ To which the proper answer is ‘Be of good cheer. You can continue in the same general line of research.’ - Bill Tutte

LeetCode - Algorithms - 171. Excel Sheet Column Number

这题算Easy,Excel列编号好像可以理解成26进制,少不了查下JDK API Specification,查看JavaScript Bible

Java

1
2
3
4
5
6
7
8
9
10
class Solution {
public int titleToNumber(String s) {
int n = 0;
int len = s.length();
for(int i=s.length()-1;i>=0;i--) {
n += (Character.getNumericValue(s.charAt(i))-9)*Math.pow(26, len-i-1);
}
return n;
}
}

Submission Detail

  • 1000 / 1000 test cases passed.
  • Your runtime beats 5.55 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {string} s
* @return {number}
*/
var titleToNumber = function(s) {
var n = 0;
var len = s.length;
for(var i=s.length-1;i>=0;i--) {
n+=(s.charCodeAt(i)-64)*Math.pow(26,len-i-1);
}
return n;
};

Submission Detail

  • 1000 / 1000 test cases passed.
  • Your runtime beats 99.02 % of javascript submissions.

LeetCode - Algorithms - 371. Sum of Two Integers

这题不Easy呀,像智力题,像脑筋急转弯。
代码是人家的,我可想不出来。真是“会者不难,难者不会”。

JavaScript

自增自减运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
if (a>0) {
while(a>0) {
a--;
b++
}
}
if (a<0) {
while(a<0) {
a++;
b--;
}
}
return b;
};

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 3.38 % of javascript submissions.

位运算+递归

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
var sum,carry;
if (b==0) return a;
sum = a^b;
carry = (a&b)<<1;
return getSum(sum,carry);
};

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 69.57 % of javascript submissions

消除递归的位运算

知其然而不知其所以然,居然可以这么做,觉得很神奇

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function(a, b) {
while(b!=0) {
var carry=a&b;
a = a^b;
b = carry<<1;
}
return a;
};

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 100.00 % of javascript submissions.

Java

消除递归的位运算

1
2
3
4
5
6
7
8
9
10
class Solution {
public int getSum(int a, int b) {
while (b!=0) {
int carry = a&b;
a = a^b;
b = carry<<1;
}
return a;
}
}

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 100.00 % of java submissions.

递归+位运算

1
2
3
4
5
6
7
8
9
class Solution {
public int getSum(int a, int b) {
int sum,carry;
if (b==0) return a;
sum = a ^ b;
carry = (a & b) << 1;
return getSum(sum,carry);
}
}

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 100.00 % of java submissions.

自增自减运算符

这个解很像脑筋急转弯,不难,但让人想不到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int getSum(int a, int b) {
if (a>0) {
while(a>0) {
a--;
b++;
}
}
if (a<0) {
while(a<0) {
a++;
b--;
}
}
return b;
}
}

Submission Detail

  • 13 / 13 test cases passed.
  • Your runtime beats 3.44 % of java submissions.

LeetCode - Algorithms - 204. Count Primes

虽然Difficulty标为Easy,但对自己来说不算简单呀,犯了各种错误。

参考网上的各种代码,才终于跑通了。 算法其实就是经典的 Sieve of Eratosthenes,复杂度 O(NloglogN)

ref

Java

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int countPrimes(int n) {
if (n<=2) return 0;
int x = 0;
int sqrt = (int) Math.sqrt(n);
boolean[] b = new boolean[n];
b[0]=b[1]=false;
for(int i=2;i<n;i++)
b[i]=true;
for(int i=2;i<=sqrt;i++) {
if (b[i]) {
for(int j=i*i;j<n;j+=i) {
b[j]=false;
}
}
}
for(int i=0;i<b.length;i++) {
if (b[i])
x++;
}
return x;
}
}

Submission Detail

  • 20 / 20 test cases passed.
  • Your runtime beats 42.53 % of java submissions.

2

这道题好像可以拿来作为范例学习Java 8 Streams:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.BitSet;
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;

class Solution {
public int countPrimes(int n) {
final BitSet sieve = new BitSet(n);
final IntSummaryStatistics stats = IntStream.rangeClosed(2, n-1)
.filter(x -> !sieve.get(x))
.peek(x -> {
if (x*x < n)
for(int i = x; i < n; i+=x)
sieve.set(i);
})
.summaryStatistics();
return new Long(stats.getCount()).intValue();
}
}

Submission Detail

  • 20 / 20 test cases passed.
  • Your runtime beats 14.45 % of java submissions.

代码更精炼了,但性能变差了

3 bottom-up approach

solution of Leetcode 204. Count Primes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int countPrimes(int n) {
boolean notPrime[] = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (!notPrime[i]) {
count++;
for (int j = 2; i * j < n; j++) {
notPrime[i * j] = true;
}
}
}
return count;
}
}

Submission Detail

  • 20 / 20 test cases passed.
  • Runtime: 13 ms, faster than 77.25% of Java online submissions for Count Primes.
  • Memory Usage: 38.3 MB, less than 5.66% of Java online submissions for Count Primes.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @param {number} n
* @return {number}
*/
var countPrimes = function(n) {
if (n<=2) return 0;
var sqrt = Math.floor(Math.sqrt(n));
var b = new Array(n);
b[0]=false;
b[1]=false;
for(var i=2;i<n;i++) b[i]=true;
for(var i=2;i<=sqrt;i++) {
if (b[i]) {
for(var j=i*i;j<n;j+=i) {
b[j]=false;
}
}
}
var x=0;
for(var i=0;i<n;i++) {
if (b[i]) x++;
}
return x;
};

Submission Detail

  • 20 / 20 test cases passed.
  • Your runtime beats 97.46 % of javascript submissions.

Java 8 用法

ref

Java 8 新特性概述
https://www.ibm.com/developerworks/cn/java/j-lo-jdk8newfeature/index.html

Java 8 被动迭代式特性介绍
https://www.ibm.com/developerworks/cn/java/j-lo-java8-iterator/index.html

使用 Java 8 作为 Java 下一代语言
评估 Java 8 是否适合代替 Java
https://www.ibm.com/developerworks/cn/java/j-jn15/index.html

Java 8 中的 Streams API 详解
Streams 的背景,以及 Java 8 中的使用详解
https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html

Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)。Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用 fork/join 并行方式来拆分任务和加速处理过程。通常编写并行代码很难而且容易出错, 但使用 Stream API 无需编写一行多线程的代码,就可以很方便地写出高性能的并发程序。所以说,Java 8 中首次出现的 java.util.stream 是一个函数式语言+多核时代综合影响的产物。

The Java 8 Stream API Tutorial
https://www.baeldung.com/java-8-streams

Java 8 Stream Tutorial
https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

Lambdas and Streams in Java 8 Libraries
http://www.drdobbs.com/jvm/lambdas-and-streams-in-java-8-libraries/240166818

Streams

数组连接成字符串

Joining Objects into a String with Java 8 Stream API

1
2
String[] strs = {"flower","flow","flight"};
System.out.println(Arrays.stream(strs).collect(Collectors.joining( "," )));

返回数组最大值

1
2
int[] arr = {2,7,3,13,59,31};
Arrays.stream(arr).max().getAsInt();

List join as String

1
2
List<Integer> primes = primeNumbersTill(100);
String s = primes.stream().map(Object::toString).collect(Collectors.joining(","));
1
2
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Stream.of(matrix).map(Arrays::toString).forEach(System.out::println);

java 8 打印素数序列

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public static boolean isPrime(int number) {
return IntStream.rangeClosed(2, number/2).noneMatch(i -> number%i == 0);
}

public static List<Integer> primeNumbersTill(int n) {
return IntStream.rangeClosed(2, n)
.filter(x -> isPrime(x)).boxed()
.collect(Collectors.toList());
}

public static void main(String[] args) {
final int n = 100;
List<Integer> primes = primeNumbersTill(n);
String s = primes.stream().map(Object::toString).collect(Collectors.joining(","));
System.out.println(s);
}

2 Sieve of Eratosthenes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public static List<Integer> primeNumber(int n) {
final BitSet sieve = new BitSet(n+1);
List<Integer> plist = IntStream.rangeClosed(2, n)
.filter(x -> !sieve.get(x))
.peek(x -> {
if (x*x < n)
for(int i = x; i <= n; i+=x)
sieve.set(i);
}).boxed()
.collect(Collectors.toList());
return plist;
}

public static void main(String[] args) {
final int n = 100;
List<Integer> plist = primeNumber(n);
System.out.println(plist.stream().map(Object::toString).collect(Collectors.joining(",")));
}

Lambda

LocalDate

1
2
3
LocalDate now = LocalDate.now();
LocalDate firstDayOfYear = now.with(TemporalAdjusters.firstDayOfYear());
System.out.println( firstDayOfYear.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) );

LeetCode - Algorithms - 14. Longest Common Prefix

此题在LeetCode上难度标为Easy,LintCode上却标为Medium

这题虽然不能脱离IDE直接刷题,但没怎么被卡住,一天之内就做完了,还算简单吧。有共同前缀的字符串,它们的首字母肯定一样。

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
var lcp = "";
if (strs==null || strs.length==0)
return lcp;
var minLen = strs[0].length;
var idx = 0;
for(var i=1;i<strs.length;i++) {
if (strs[i].length<minLen) {
minLen = strs[i].length;
idx = i;
}
}
var lcp = "";
var ch = strs[idx].charAt(0);
var b = true;
for(var i=0;i<strs.length;i++) {
b = b && strs[i].charAt(0)==ch?true:false;
}
if (b) {
lcp+=ch;
for(var j=1;j<minLen;j++) {
ch = strs[idx].charAt(j);
b = true;
for(var i=0;i<strs.length;i++) {
b = b && (strs[i].charAt(j)==ch?true:false);
}
if (b)
lcp += ch;
}
}
return lcp;
};

Submission Detail

  • 118 / 118 test cases passed.
  • Your runtime beats 81.84 % of javascript submissions.

如果在

1
2
if (b)
lcp += ch;

后面加个break语句用于跳出循环判断,改成

1
2
3
4
if (b)
lcp += ch;
else
break;

性能倒反降低了,这个有点不明白?

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs==null || strs.length==0) return "";
int minStrLen = strs[0].length();
int idx = 0;
for(int i=1;i<strs.length;i++) {
if (strs[i].length()<minStrLen) {
minStrLen = strs[i].length();
idx = i;
}
}
StringBuilder lcp = new StringBuilder();
if (strs[idx]!=null && strs[idx].length()>0) {
char ch = strs[idx].charAt(0);
boolean b = true;
for(int i=0;i<strs.length;i++) {
b = b && (strs[i].charAt(0)==ch?true:false);
}
if (b) {
lcp.append(ch);
for(int j=1;j<minStrLen;j++) {
ch = strs[idx].charAt(j);
b = true;
for(int i=0;i<strs.length;i++) {
b = b && (strs[i].charAt(j)==ch?true:false);
}
if (b) {
lcp.append(ch);
}
else {
break;
}
}
}
}
return lcp.toString();
}
}

Submission Detail

  • 118 / 118 test cases passed.
  • Your runtime beats 11.84 % of java submissions.

跟js代码的情况一样,加了跳出循环判断的break语句

1
2
3
4
5
6
if (b) {
lcp.append(ch);
}
else {
break;
}

性能倒反降低,不解?