JavaScript solution exceeds the limit but Java not


  • 0
    L

    This JavaScript solution works but exceeds the time limit. However, the Java solution with the same code pass.

    Can anyone tell me the reason? Thank you.

    Here is the JavaScript solution, following by Java solution

    
    var subarraySum = function(nums, k) {
        var total = 0;
        var acc = accuArr(nums);
        for(let i=0;i<nums.length;i++){
            for(let j=i;j<nums.length;j++){
                if(accSum(acc, i, j+1) == k){
                    total ++;
                }
            }
        }
        return total;
    };
    
    function accuArr(arr){
        var acc = [0],sum=0;
        for(let i=0;i<arr.length;i++){
            sum+=arr[i];
            acc.push(sum);
        }
        return acc;
    }
    
    function accSum(arr, a, b){
        return arr[b]-arr[a];
    }
    
    public class Solution {
        public int subarraySum(int[] nums, int k) {
            int total = 0;
            List<Integer> acc = accuArr(nums);
            for(int i=0;i<nums.length;i++){
                for(int j=i;j<nums.length;j++){
                    if(accSum(acc, i, j+1) == k){
                        total ++;
                    }
                }
            }
            return total;
            }
        public List<Integer> accuArr(int[] arr){
        
            List<Integer> acc = new ArrayList<Integer>(); 
            int sum=0;acc.add(sum);
            for(int i=0;i<arr.length;i++){
                sum+=arr[i];
                acc.add(sum);
            }
            return acc;
        }
        
        public int accSum(List<Integer>arr, int a, int b){
            return arr.get(b)-arr.get(a);
        }
    }
    

Log in to reply
 

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