/images/gravatar2.jpg

Steven Lin

[Golang][Leetcode][Array]刷題系列-54-Spiral Matrix

54. Spiral Matrix Level : Medium 原題連結 :Click 題目 : Given an m x n matrix, return all elements of the matrix in spiral order. Example : Note Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] 以下是我自己的解法 - O(m*n) Runtime: 0 ms, faster than 100.00% of Go online submissions for Spiral Matrix. 解題思路 : 這題與59題非常類似 首先題目要求螺旋式的從2D matrix中取出element 這個題目沒有特別的解法就是純粹需要設定好 “邊界條件” & “堅持循環不變量原則(與binary search相同)” 所以需要模擬順時針填入矩陣的過程 解法 :

[Golang][Leetcode][Array]刷題系列-59-Spiral Matrix

59. Spiral Matrix II Level : Medium 原題連結 :Click 題目 : Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order. Example : Note Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] 以下是我自己的解法 - O(n^2) Runtime: 0 ms, faster than 100.00% of Go online submissions for Spiral Matrix II. 解題思路 : 首先題目要求螺旋式的從外面向裡面填入數字到n*n矩陣從1開始直到填滿,所以會填到n*n個數字進去 這個題目沒有特別的解法就是純粹需要設定好 “邊界條件” & “堅持循環不變量原則(與binary search相同)” 所以需要模擬順時針填入矩陣的過程 解法 :

[Golang][Leetcode][Array]刷題系列-209-Slide Window

209. Minimum Size Subarray Sum Level : Medium 原題連結 :Click 題目 : Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, …, numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. Example : Note Input: target = 7, nums = [2,3,1,2,4,3] Output: 2

[Golang][Leetcode][Array]刷題系列-977-Two Pointers

977. Squares of a Sorted Array Level : Easy 原題連結 :Click 題目 : Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example : Note Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. 解題思路 : 暴力解法 : 直接先遍歷一次將全部elements平方後,再sorting 這樣的話,time complexity is O(n + nlgn),也可以寫成O(nlogn),two pointers解法會快上取多 Two Pointers解法 :

[Golang][Leetcode][Array]刷題系列-27-Two Pointers

27. Remove Element Level : Easy 原題連結 :Click 題目 : Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result.

[Golang][Leetcode][Array]刷題系列-34-Binary Search

34. Find First and Last Position of Element in Sorted Array Level : Medium 原題連結 :Click 題目 : Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. Example : Note Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]