Skip to content

Commit de66880

Browse files
author
Chris Wu
committed
no message
1 parent 39884b7 commit de66880

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

problems/move-zeroes.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,23 @@ def moveZeroes(self, nums):
1818
temp = nums[cursor]
1919
nums[cursor] = nums[i]
2020
nums[i] = temp
21-
cursor+=1
21+
cursor+=1
22+
23+
24+
"""
25+
j is the index to insert when a number not equal to 0.
26+
After all the non-zero numbers are inplace, the rests are all zeros.
27+
"""
28+
class Solution(object):
29+
def moveZeroes(self, nums):
30+
j = 0
31+
32+
for n in nums:
33+
if n!=0:
34+
nums[j] = n
35+
j += 1
36+
37+
for i in xrange(j, len(nums)):
38+
nums[i] = 0
39+
40+
return nums
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
"""
2+
j is the index to insert when a "new" number are found.
3+
For each iteration, nums[:j] is the output result we currently have.
4+
So nums[i] should check with nums[j-1] and nums[j-2].
5+
"""
6+
class Solution(object):
7+
def removeDuplicates(self, nums):
8+
j = 2
9+
10+
for i in xrange(2, len(nums)):
11+
if not (nums[i]==nums[j-1] and nums[i]==nums[j-2]):
12+
nums[j] = nums[i]
13+
j += 1
14+
return j

problems/remove-element.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""
2+
j is the index to insert when a number not equal to val.
3+
j will never catch up i, so j will not mess up the check.
4+
"""
5+
class Solution(object):
6+
def removeElement(self, nums, val):
7+
j = 0
8+
for n in nums:
9+
if n!=val:
10+
nums[j] = n
11+
j += 1
12+
return j

0 commit comments

Comments
 (0)