0
点赞
收藏
分享

微信扫一扫

[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: 3
Explanation:
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: 2
Explanation: 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:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. 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]<A[i+1]):
decreasing=False
return increasing or decreasing

参考文献

​​[LeetCode] Approach 3: One Pass (Simple Variant)​​


举报

相关推荐

0 条评论