Daily emulation — bytes

Given an integer array A, returns the number of (continuous, non-empty) subarrays in which the sum of the elements is divisible by K.

Example: input: A = [4,5,0,-2,-3,1], K = 5 output: 7 explanation: there are 7 subarrays whose sum of elements is divisible by K = 5: [4, 5, 0, 2, 3, 1], [5], [5, 0], [5, 0, 2, 3], [0], [0, 2, 3], [2, 3]Copy the code

/** * @parse * 1. Traversal twice -- timed out */
var subarraysDivByK = function (A, K) {
    let res = 0

    for (let i = 0; i < A.length; i++) {
        let temp = 0
        for (let j = i ; j < A.length; j++) {
            temp+= A[j]
            if(! (temp % K)) { res +=1}}}return res
};

/** * @analysis * 1. Non-fixed length sliding window */
var subarraysDivByK = function (A, K) {
    let res = 0

    // The maximum size of the window is A.length-1 and the minimum size is 1
    for(let i =1; i<A.length+1; i++){let temp = 0
        let current = 0
        // Initialize the window
        while(current<i){
            temp+=A[current]
            current++
        }
        // Slide window
        while(current<A.length){
            if(temp % K==0) res++
            temp = temp-A[current-i]+A[current]
            current++
        }
            if(temp % K==0) res++
    }

    return res
}

Copy the code

feeling

  • Recently, I read some non-technical articles, including learning, writing, investment and so on, and gradually fine-tuned my plan. Of course, the annual route, early rise + algorithm + output remains the same, but the selection does change
  • It’s good to do single class questions all the time, and I might be able to have a deeper understanding of this kind of questions after I finish them, but what is the purpose of brushing them
  • And then I went on to read that “technology serves the business”, so why should algorithms serve the business?
  • So I still have to go back to the beginning, the beginning of my algorithm, at least back to the last unfinished goal, what was it? Obviously, preparing for a big company interview
  • Maybe AFTER I have met dachang, I will gradually strengthen myself, but the real problem is that if I only brush part of the questions, I will not succeed in the interview, but I do not have more time to do the algorithm, because dachang does not have a single algorithm, so I have to make a choice first and brush the real questions of dachang;
  • LC has a very interesting function, which is to simulate the interview, each time three questions, one and a half hours, which are selected from the LC question bank, the credibility is quite high, so I take this as the goal.
  • After one month, I was able to pass the mock interview within the specified time.
  • Don’t be around the bustling lost the original purpose, technology is just a means, just a tool, just a way to achieve the goal, don’t indulge in technology, let alone technology is not good.

Above, mutual encouragement!