iT邦幫忙

2021 iThome 鐵人賽

DAY 3
1

今日題目:48. Rotate Image

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

https://ithelp.ithome.com.tw/upload/images/20210918/20140843EgLTp6qkiK.png
https://ithelp.ithome.com.tw/upload/images/20210918/20140843wdyOCSA4yg.png

Example 3:
Input: matrix = [[1]]
Output: [[1]]

Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

Constraints:

  • matrix.length == n
  • matrix[i].length == n
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

思路:

因題目為rotate by 90 degrees,所以我由the last row之 first column開始,從下向上取,
取完的一個column,即為rotate後的row

My solution:

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
    n = len(matrix)

    for i in range(n):
        ans = []
        for j in range(n - 1, -1, -1):
            ans.append(matrix[j][i])
        matrix.append(ans)

    del matrix[0:2]

Result:

https://ithelp.ithome.com.tw/upload/images/20210918/20140843IvMr0WIvRE.png

檢討:

後來看其他人的solution,看到一些不錯的方法
像是分為兩部分,先將 matrix transpose後,再對each row進行reflect
是一個可以更直接想到的方法!!

今日題目2: 136. Single Number

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:
Input: nums = [2,2,1]
Output: 1

Example 2:
Input: nums = [4,1,2,1,2]
Output: 4

Example 3:
Input: nums = [1]
Output: 1

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

思路:

建一個list放一個第一次出現的element,將nums內的elements和list比較,如沒有則append進去,如已在內則remove

My solution:

class Solution(object):
    def singleNumber(self, nums):

        ans = []
        for n in nums:
            if n in ans:
                ans.remove(n)
            else:
                ans.append(n)
        return(ans[0])

Result:

https://ithelp.ithome.com.tw/upload/images/20210918/20140843Gugg5EZs1s.png

檢討:

所花費的時間和memory都太多了,看了其他討論區的solution
有以下兩種酷酷的
第一個:

def singleNumber2(self, nums):
    res = 0
    for num in nums:
        res ^= num
    return res

第二個:

def singleNumber3(self, nums):
    return 2*sum(set(nums))-sum(nums)

給大家參考參考!!

以上報告完畢
明天見


上一篇
Day2-LeetCode 118. Pascal's Triangle
下一篇
Day4- 15. 3Sum
系列文
開學之前....20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿瑜
iT邦研究生 4 級 ‧ 2021-09-18 23:28:39

哇賽!!! Code 簡潔有力。
題目2李臻在動物園有跟我分享XOR法(實在神奇)

我要留言

立即登入留言