my java solution beats 99% but with a question


  • 0
    public int[] maxSlidingWindow(int[] nums, int k) {
            if(nums.length < 1) return new int[0];
            int n = nums.length - k + 1;
            int[] res = new int[n];
            int maxIndex = -1, maxValue = Integer.MIN_VALUE;
            
            for(int i = k - 1;i < nums.length;i++) {           
                if(maxIndex == -1) {
                    maxValue = Integer.MIN_VALUE;
                    for(int j = i;j > i - k;j--) {
                        if(nums[j] > maxValue) {
                            maxIndex = j;
                            maxValue = nums[j];
                        }
                    }
                }
                if(nums[i] >= maxValue) {
                    maxValue = nums[i];
                    maxIndex = i;
                }
                res[i - k + 1] = maxValue;
                if(maxIndex == i - k + 1) maxIndex = -1;
            }
            
            return res;
        }
    
    But I am quite confused: does faster means better, especially in practice or in an interview? A solution using deque for this question seems much wiser, but in practice, deque works slower and worst case would not be that worse. So in average cases, no deque solution could work better. Then, which one is the better solution?

Log in to reply
 

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