leetcode學習筆記1437 Check If All 1‘s Are at Least Length K Places Away
阿新 • • 發佈:2021-01-26
leetcode學習筆記1437
問題
Check If All 1’s Are at Least Length K Places Away
檢查是否所有的1之間的間隔都至少是k.
Example 1:
Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.
Example 2:
Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
Example 3:
Input: nums = [1,1,1,1,1], k = 0
Output: true
Example 4:
Input: nums = [0,1,0,1], k = 1
Output: true
Constraints:
- 1 <= nums.length <= 105
- 0 <= k <= nums.length
- nums[i] is 0 or 1
方法1
遍歷,依次計算所有1之間的距離.
時間複雜度O(n).
空間複雜度O(1).
class Solution {
public boolean kLengthApart(int[] nums, int k) {
if(k == 0)
return true;
int left = -1;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0)
continue;
if(left < 0)
left = i;
else{
if(i - left - 1 < k)
return false;
else
left = i;
}
}
return true;
}
}