代码随想录算法训练营第二天|977, 209, 59

1,040 阅读1分钟

977. Squares of a Sorted Arrays

It's another typical question for two points. The main point is the minimum number could be the biggest one after squares if the value is negative. So I declared two points at start point and end point,respectively. Then we can do comparison for absolute values which both pointer point to. After that, we can get the bigger one and put it from the end of the array we are going to return. Only move the pointer pointing to bigger element(absolute).

image.png

209. Minimum size subarray sum

In this question, the slide window concept would be applied. We should find first subarray whose sum is equal to or greater than the target number given, then document it via a variable. After that, remove the first elment of current window to see whether it's still valid, if so, replace the shorest length with current window size. When the sum of current window is less than target, we can move the other pointer forward until the sum of window reach the target again, and repeat previous process. During the process, we should compare each valid window size with shortest length we documented, and replace it by the smaller value. image.png

59. Spiral Matrix II

Even though this question is a medium level question, it's not that hard to figure it out logically. From my perspective, it's more of an examination for interpreting the logic from real life to code. We should declare for edges which are starting row, ending row, starting column and ending column, respectively. Through that, we can start documenting elements located at the edges of the array. After we've covered all edges, we shrink the matrix then deal with it with same process. In this question, edge cases and requirements are relatively more complex. For example, we should avoid repeatedly visiting one slot, if startRow == endRow but startCol != endCol or vice versa.

image.png