-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtransform-array-to-all-equal-elements.py
More file actions
49 lines (44 loc) · 1.13 KB
/
transform-array-to-all-equal-elements.py
File metadata and controls
49 lines (44 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Time: O(n)
# Space: O(1)
# greedy
class Solution(object):
def canMakeEqual(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def check(target):
cnt = 0
sign = 1
for i in xrange(len(nums)):
if nums[i]*sign == target:
sign = 1
continue
cnt += 1
if i+1 == len(nums) or cnt > k:
return False
sign = -1
return True
return check(1) or check(-1)
# Time: O(n)
# Space: O(1)
# greedy
class Solution2(object):
def canMakeEqual(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def check(target):
parity = cnt = 0
for i in xrange(len(nums)):
if nums[i] == target:
continue
cnt += i if parity else -i
if cnt > k:
return False
parity ^= 1
return parity == 0
return check(1) or check(-1)