程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

LeeCode - all elements in the array is equal to zero (python)

編輯:Python

Gives you an array nums of non-negative integers.In one step, you must:

Select a positive integer x that is less than or equal to the non-zero element of nums that is the smallest.
Subtract x from each positive integer in nums.
Returns the minimum number of operations required to make all elements in nums equal to 0.

Example 1:

Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
Step 1: Select x = 1, then nums = [0,4,0,2,4] .
Step 2: choose x = 2 , then nums = [0,2,0,0,2] .
Step 3: Choose x = 2 , then nums = [0,0,0,0,0] .

Example 2:

Input: nums = [0]
Output: 0
Explanation: Every element in nums is already 0 , so nothing needs to be done.

Tip:

1 <= nums.length <= 100
0 <= nums[i] <= 100

Source: LeetCode
Link: https://leetcode.cn/problems/make-array-zero-by-subtracting-equal-amounts
The copyright belongs to LeetCode.com.For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

# -*- coding: utf-8 -*-# @Time : 2022/7/6 14:51# @Author : Ling Xianwen# @Email : [email protected] typing import Listclass Solution:def minimumOperations(self, nums: List[int]) -> int:# return count parameter countcount = 0while True:# copy array to xx = nums.copy()nums = set(x)# remove 0 from the arrayif 0 in nums:nums.remove(0)#if len(nums) == 0:breakn = min(nums)# Array minus the smallest each time;# steps worth learning;nums = [i - n for i in nums]count += 1return countif __name__ == '__main__':sol = Solution()print(sol.minimumOperations([1, 5, 0, 3, 5]))


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved