Basic Java solution


  • 4
    public int subarraySum(int[] nums, int k) {
            int count=0;
            for(int i=0;i<nums.length;i++){
                int sum=nums[i];
                if(sum==k){
                    count++;
                }
                for(int j=i+1;j<nums.length;j++){
                    sum+=nums[j];
                    if(sum==k) count++;
                }
            }
            return count;
        }
    

  • 1

    Nice solution, it's O(n^2) but easier to understand.

    I had similar implementation:

        public int subarraySum(int[] nums, int k) {
            int res = 0;
            if (nums == null || nums.length == 0) return 0;
            for (int i = 0; i < nums.length; i++) {
                int temp = k;
                for (int j = i; j >= 0; j--) {
                    temp = temp - nums[j];
                    if (temp == 0) res++;
                }
            }
            return res;
        }
    

  • 1
    D

    Nice Solution, easy to understand. Failed as TLE when I tried to implement on Python.


Log in to reply
 

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