Why my Java solution so fast? (16ms)


  • 0

    Okay...I am really wondering why...the following version gives me 16ms evaluation:

    public class Solution {
        public int firstUniqChar(String s) {
            int[] pos = new int[26];
            for(int i=0;i<26;++i) pos[i] = -1;
            char[] arr = s.toCharArray();
            for(int i=0;i<arr.length;++i) {
                int idx = arr[i] - 'a';
                if(pos[idx] == -1) pos[idx] = i;
                else pos[idx] = -2;
            }
    
            int ret = arr.length;
            for(int i=0;i<26;++i) {
                if(pos[i] >= 0 && ret > pos[i]) {
                    ret = pos[i];
                }
            }
            return ret == arr.length ? -1 : ret;
        }
    }
    

    However if I don't convert the string to char array but rather manipulate it directly(which I thought it is faster because I don't need copy), the runtime drops to 29ms....

    public class Solution {
        public int firstUniqChar(String s) {
            int[] pos = new int[26];
            for(int i=0;i<26;++i) pos[i] = -1;
            for(int i=0;i<s.length();++i) {
                int idx = s.charAt(i) - 'a';
                if(pos[idx] == -1) pos[idx] = i;
                else pos[idx] = -2;
            }
    
            int ret = s.length();
            for(int i=0;i<26;++i) {
                if(pos[i] >= 0 && ret > pos[i]) {
                    ret = pos[i];
                }
            }
            return ret == s.length() ? -1 : ret;
        }
    }
    

    Why String in Java so slow? because of synchronization or something?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.