Skip to content

Commit 31c7287

Browse files
committed
Solutions for problem similar to binary search, array
1 parent 0ac8235 commit 31c7287

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

400-500Q/442.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''
2+
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
3+
4+
Find all the elements that appear twice in this array.
5+
6+
Could you do it without extra space and in O(n) runtime?
7+
8+
Example:
9+
Input:
10+
[4,3,2,7,8,2,3,1]
11+
12+
Output:
13+
[2,3]
14+
'''
15+
16+
class Solution(object):
17+
def findDuplicates(self, nums):
18+
"""
19+
:type nums: List[int]
20+
:rtype: List[int]
21+
"""
22+
if not nums:
23+
return []
24+
25+
result = []
26+
for _, num in enumerate(nums):
27+
index = abs(num)-1
28+
if nums[index] < 0:
29+
result.append(index+1)
30+
nums[index]*=-1
31+
return result

400-500Q/448.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
3+
4+
Find all the elements of [1, n] inclusive that do not appear in this array.
5+
6+
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
7+
8+
Example:
9+
10+
Input:
11+
[4,3,2,7,8,2,3,1]
12+
13+
Output:
14+
[5,6]
15+
'''
16+
17+
class Solution(object):
18+
def findDisappearedNumbers(self, nums):
19+
"""
20+
:type nums: List[int]
21+
:rtype: List[int]
22+
"""
23+
if not nums:
24+
return []
25+
result = []
26+
for num in nums:
27+
index = abs(num)-1
28+
if nums[index] > 0:
29+
nums[index]*=-1
30+
for index, num in enumerate(nums):
31+
if num >0:
32+
result.append(index+1)
33+
return result

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ Python solution of problems from [LeetCode](https://leetcode.com/).
8989
| # | Title | Solution | Difficulty |
9090
|---| ----- | -------- | ---------- |
9191
|454|[4Sum II](https://leetcode.com/problems/4sum-ii/)|[Python](./400-500Q/454.py)|Medium|
92+
|448|[Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array)|[Python](./400-500q/448.py)|Easy|
93+
|442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array)|[Python](./400-500q/442.py)|Easy|
9294
|410|[Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) | [Python](./400-500Q/410.py)|Hard|
9395

9496

0 commit comments

Comments
 (0)