3550. Smallest Index With Digit Sum Equal to Index 解題紀錄

You are given an integer array nums. Return the smallest index i such that the sum of the digits of nums[i] is equal to i. If no such index exists, return -1.   Example 1: Input: nums = [1,3,2] Output: 2 Explanation: For nums[2] = 2, the sum of digits is 2, which is equal to index i = 2. Thus, the output is 2. Example 2: Input: nums = [1,10,11] Output: 1 Explanation: For nums[1] = 10, the sum of digits is 1 + 0 = 1, which is equal to index i = 1. For nums[2] = 11, the sum of digits is 1 + 1 = 2, which is equal to index i = 2. Since index 1 is the smallest, the output is 1. Example 3: Input: nums = [1,2,3] Output: -1 Explanation: Since no index satisfies the condition, the output is -1.   Constraints: 1 <= nums.length <= 100 0 <= nums[i] <= 1000 今天是腦袋放鬆日。 題目問我們給我們一個一維非負整數陣列 nums, 最早使 digitSum 等於索引的是哪個? 這題就是一路做 digitSum 就行了(#。 早停條件可以設定 digitSum 要小於等於 i, 等於是為了考慮後綴 0 的情況。 C++程式碼:
megapx
假設 nums 的長度是 N。 計算複雜度:O(N) -> nums[i] <= 1000,所以最多 O(4*N) ~= O(N) 空間複雜度:O(1) Github程式碼:
愛心
81
留言
encourage first comment
有些話想說嗎 快分享出來彼此交流吧!