使用范围会影响Java代码的运行时性能吗?

时间:2018-07-03 19:51:12

标签: java

我正在解决有关leetcode的以下问题: https://leetcode.com/problems/first-unique-character-in-a-string/description/

我用下面的代码花了39毫秒解决了这个问题:

class Solution {
    public int firstUniqChar(String s) {

        int[] counter = new int[26];

        for(int i=0; i<s.length(); i++)
            counter[s.charAt(i)-'a']++;

        for(int i=0; i<s.length(); i++){
            if(counter[s.charAt(i)-'a'] == 1)
                return i;
        }
        return -1;
    }
}

我检查了其他解决方案,发现以下解决方案花费了26毫秒。

class Solution {
    public int firstUniqChar(String s) {
        int[] count = new int[26];
        for(int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
        for(int i = 0; i < s.length(); i++) if(count[s.charAt(i) - 'a'] == 1) return i;
        return -1;
    }
}

如您所见,唯一的区别是第二种解决方案使用的代码行更少。性能差异来自何处?

0 个答案:

没有答案