Leetcode Biweekly Contest 76
這次的 Contest 對應 GMT+8 剛好是 22:30 ~ 24:00,但這天我到家時已經 23:00 多了,而且還沒洗澡,為了不影響成績那些的還是寫了一題。
2239. Find Closest Number to Zero
Difficulty: Easy
Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.
1 | Input: nums = [-4,-2,1,4,8] |
1 | Input: nums = [2,-1,1] |
1 <= n <= 1000-105 <= nums[i] <= 105
Solution
- 正負都要找最靠近 0 的,所以要一個
正無限大與負無限大 - 接著把 list 走過一遍:
若為正數,將該數和已儲存的最小正數比較,並存下小的;
若為負數,將該數和已儲存的最大負數比較,並存下大的;
若為 0,直接回傳 0,我相信沒有一個數可以比 0 更靠近 0。 - 將
最靠近 0 的正數與最靠近 0 的負數的絕對值比較:
若最靠近 0 的正數比較大, 回傳最靠近 0 的負數的絕對值;
若最靠近 0 的負數大於等於, 回傳最靠近 0 的正數; - Edge case: 正負數絕對值後相等,題目說此時要回傳較大的數,也就是正數,所以使用
<=。
1 | class Solution: |