# LeetCode Data Structure II
## Array
### 136. Single Number
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
```
Input: nums = [2,2,1]
Output: 1
```
```python
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = nums[0]
for i in range(1,len(nums)):
res = res ^ nums[i]
return res
```
### 169. Majority Element
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
```
Input: nums = [3,2,3]
Output: 3
```
```python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums = sorted(nums)
return nums[int(len(nums) / 2)]
```
### 15. 3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
```
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
```
**Approach**
1. Sort the list first
2. From left to right, let the element be the nums[i]
3. If we fix one of the numbers say x, we are left with the two-sum problem at hand
4. For the two sum problem, if the list is sorted, we can use two pointers to solve the problem
```python
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for idx, val in enumerate(nums):
if idx > 0 and val == nums[idx - 1]:
continue
l, r = idx + 1, len(nums) - 1
while l < r:
threeSum = val + nums[l] + nums[r]
if threeSum > 0:
r -= 1
elif threeSum < 0:
l += 1
else:
res.append([val, nums[l], nums[r]])
l += 1
while nums[l] == nums[l - 1] and l < r:
l += 1
return res
```
### 75. Sort Colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
```
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
```
**Approach**
1. Use two pointers left and right, and go through the list, if we meet 0, then swap with the value of left pointer, and if we weet 2, swap with the value of right pointer
2. Notice that the left pointer will always points to 0 or 1 since 2 will swap to the right side, but the right pointer will points to 0, 1, 2, so it might occur that 0 be swapped to the middle
https://www.youtube.com/watch?v=4xbWSRZHqac
```python
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
l, r = 0, len(nums) - 1
idx = 0
while idx <= r:
if nums[idx] == 0:
nums[idx], nums[l] = nums[l], nums[idx]
l += 1
elif nums[idx] == 2:
nums[idx], nums[r] = nums[r], nums[idx]
r -= 1
idx -= 1
idx += 1
return nums
```
### 56. Merge Intervals
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
```
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
```
### 706. Design HashMap
Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap class:
MyHashMap() initializes the object with an empty map.
void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
```
Input
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output
[null, null, null, 1, -1, null, 1, null, -1]
Explanation
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now [[1,1]]
myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]
```
```python
class MyHashMap:
def __init__(self):
self.l = [-1 for _ in range(1000001)]
def put(self, key: int, value: int) -> None:
self.l[key] = value
def get(self, key: int) -> int:
return self.l[key]
def remove(self, key: int) -> None:
self.l[key] = -1
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
```
### 56. Merge Intervals
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
```
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
```
```python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) == 1:
return intervals
intervals.sort(key = lambda x: x[0])
res = []
for interval in intervals:
if not res or interval[0] > res[-1][1]:
res.append(interval)
else:
res[-1][1] = max(interval[1], res[-1][1])
return res
```
### 48. Rotate Image
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

```
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
```
**Approach**
1. Reverse diagonally
2. Reverse left and right
```python
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
r, c = len(matrix), len(matrix[0])
def diagonal(matrix):
for col in range(c):
row = 0
while row <= col:
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
row += 1
def LRreverse(matrix):
mid = r // 2
for col in range(mid):
for row in range(r):
matrix[row][col], matrix[row][c - col - 1] = matrix[row][c - col - 1], matrix[row][col]
diagonal(matrix)
LRreverse(matrix)
return matrix
```