洞察探索如何通过一套代码实现跨平台小程序开发与高效管理,助力企业数字化转型
670
2022-08-22
[leetcode] 896. Monotonic Array
Description
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain. Example 1:
Input: candies = [1,1,2,2,3,3]Output: 3Explanation:There are three different kinds of candies (1, 2 and 3), and two candies for each kind.Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3]Output: 2Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.
Note:
The length of the given array is in range [2, 10,000], and will be even.The number in given array is in range [-100,000, 100,000].
分析
题目的意思是:判断一个list是否是单调递增数列或者递减数列,代码一是我自己实现的一个版本,用了两个循环,时间复杂度O(2n)。代码二用到了一个循环,解法比较巧妙,时间复杂度O(n)。
代码一
class Solution: def isMonotonic(self, A: List[int]) -> bool: flag=False for i in range(len(A)-1): if(A[i]<=A[i+1]): flag=True else: flag=False break if(flag): return True for i in range(len(A)-1): if(A[i]>=A[i+1]): flag=True else: return False return True
代码二
class Solution: def isMonotonic(self, A: List[int]) -> bool: increasing=True decreasing=True for i in range(len(A)-1): if(A[i]>A[i+1]): increasing=False if(A[i] 参考文献 [LeetCode] Approach 3: One Pass (Simple Variant)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~