[Leetcode] A sub-array with the sum of K Yuan Chu’s selected questions

Title description: 560 sum is a sub-array of K

Given an integer array and an integer k, you need to find the number of consecutive sub-arrays that sum to k in the array.

Example 1:

输入:nums = [1,1,1], k = 2
输出: 2 

Explanation: [1,1] and [1,1] are two different situations.

Example 2:

输入:nums = [1,1,1,0], k = 2
输出: 3 

Explanation: [1,1],[1,1],[1,1,0] are all

Example 3:

输入:nums = [-1,1,1,0], k = 2
输出: 2

Explanation: [1,1], [1,1,0] are both

The subject requirements are well understood, but we must first consider all the circumstances that will happen, because it is an int type array, so the integer type inside is nothing more than less than zero, equal to 0, and greater than zero. So when we are doing this topic, we need to consider a situation that is the case where the array contains 0. For example, in Example 2, [1,1], [1,1,0] are all sub-arrays, and this cannot be omitted. Happening. Some students who are just starting to brush the questions may not think of this situation, and only one example is given in the original question example, so some special situations are not expected, but as the number of questions you brush increases, your ability to analyze the questions will be better. The stronger you come, you can think of some special examples first when you get a question.

First, let’s talk about the violent solution

Note: We can easily think of the violent method, but the time complexity of the violent method tends to be relatively high. Although the time complexity is relatively high, we must not ignore the violent solution (especially when encountering problems that have no idea) and In many cases, other solutions are optimizations of the violent method, so when we do the problem, we shouldn't be superior and ignore the violent method. Instead, try to optimize the brute force method.

The idea of ​​the brute force method is very simple, it is a double loop, accumulate nums[j], when the sum is K value, the counter is increased by 1. After the traversal is over, the value is returned. The brute force method is also applicable to the situation where 0 exists, because sum + 0, the value is still sum, if sum is equal to k at this time, the counter will still increase by one.

Insert picture description here

Question code:

class Solution {
    
    
    public int subarraySum(int[] nums, int k) {
    
    
          if(nums.length == 0){
    
    
              return 0;
          }  
          //计数器
          int count = 0;
          //代表的是蓝指针的运动轨迹
          for(int i =0;i<nums.length;i++){
    
    
              int sum = 0;
              //代表橙指针的运动轨迹
              for(int j =i;j<nums.length;j++){
    
    
                  //将橙指针遍历的值进行相加
                  sum += nums[j];
                  //等于时计数器加1
                  if(sum == k){
    
    
                      count++;
                      //这里不可以break,因为可能有这种情况k=1数组为[1,0,0,1,-1]这个情况
                  }                  
              }
          }
          return count;
    }
}

Hashmap法:

This method is more ingenious. There are several questions in Leetcode that can use this method, so I hope that readers can take a closer look at this method. It may seem a bit difficult at the beginning of the question, but we can discuss it together.

Let's take a look at the change in the value of sum

sum[0]=nums[0];

sum[1]=nums[0]+nums[1];

sum[2]=nums[0]+nums[1]+nums[2];

sum[3]=nums[0]+nums[1]+nums[2]+nums[3];

Because sum[3]=sum[2]+nums[3], so sum[3]-sum[2]=nums[3],sum[3]-sum[1]=nums[2]+nums[3 ];

Through the above formula, we know that sum[j]-sum[i]=k, and the transformation is sum[j]-k=sum[i]; this problem has become the number of appearances of sum[i].

Insert picture description here

Insert picture description here

class Solution {
    
           
    public int subarraySum(int[] nums, int k) {
    
    
        int count = 0;//计数器
        if(nums.length < 1){
    
    
            return 0;
        }
        //hashmap用来存sum[i]的和出现的次数
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0,1);//防止这种情况,数组只有一个1,k=1则count=1
        int sum = 0;
        for(int i = 0; i<nums.length; i++){
    
    
           sum += nums[i];//累加
            //获取sum-k出现的个数,例当前指针在第j位。sum[j]=10,k=2,
            //则需要知道sum[i]=8时,共有几种情况,sum[i]代表的是前i位的值
           if(map.containsKey(sum - k)){
    
    
               count += map.get(sum-k);//获取次数
           }
           map.put(sum,map.getOrDefault(sum,0)+1);//没出现则存入一次
       }
       return count;
    }
    
}

Guess you like

Origin blog.csdn.net/tan45du_yuan/article/details/109297850