目录
- Array
- Easy
- 219. Contains Duplicate II
- Question: Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
- 217. Contains Duplicate
- Question: Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
- 66. Plus One
- Question: Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list.
- 67. Add Binary
- Question: Given two binary strings, return their sum (also a binary string).
- 228. Summary Ranges
- Question: Given a sorted integer array without duplicates, return the summary of its ranges.
- 189. Rotate Array
- Question: Rotate an array of n elements to the right by k steps.
- 27. Remove Element
- Question: Given an array and a value, remove all instances of that value in place and return the new length.
- 26. Remove Duplicates from Sorted Array
- Question: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
- 1. Two Sum
- Question: Given an array of integers, return indices of the two numbers such that they add up to a specific target.
- 118. Pascal's Triangle My Submissions Question
- Question: Given numRows, generate the first numRows of Pascal's triangle.
- 119. Pascal's Triangle II
- Question: Given an index k, return the kth row of the Pascal's triangle.
- 283. Move Zeroes
- Question: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
- 88. Merge Sorted Array
- Question: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
- 169. Majority Element
- Question: Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
- Medium
- Easy
@(Leetcode)
Array
Easy
219. Contains Duplicate II
Question: Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
Idea: Using hashmap, array value save as key and index save as values in the map, then judge whether the map contain key = nums[i], and get value through the key, judge the distance between index i and map values.
Time and space complex:
Time complex: O(N)
Space complex: O(N)
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i]) && (i - map.get(nums[i])) <= k ) {
return true;
}
map.put(nums[i], i);
}
return false;
}
}
No bug free: erro to judge the distance between i and map value is less than k, (i - map.get(nums[i]) <= k)
write into (i - map.get(nums[i]) == k)
217. Contains Duplicate
Question: Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Idea: Using hash set to save the array values, if the set has already cantains the value, return true, else return false.
Other idea: O(N^2) : two loop, judge nums[i] == nums[j]
O(N log (N)): sort array first, then O(N) loop to judge whether the previous value equal to its following values nums[i] == nums[i+ 1]Time and space complex: O(N) : Using hash set
public class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet set = new HashSet();
for(int i = 0; i < nums.length; i++) {
if(set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
}
return false;
}
}
Not bug free : Error using set method set.put(value)
, right method is set.add(value)
66. Plus One
Question: Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list.
Idea: Carefull about the problem and it said the most significant digit is at the head of the list, so Array digits[0] is the must the significant number. What we need to do is check the lowest digit of the number, which means that from the
digits[digits.length - 1]
to check whether there is a digit less than 9, if there is, let this digit plus one and return, else means the number is all 9, increase the array one bit and let the highest bit of the number(digits[0]) set to 1.Time complex: O(N)
Space complex: O(1)
public class Solution {
public int[] plusOne(int[] digits) {
// 1 2 3 4 5 find a number less than 9 can let it plus one and return
for(int i = digits.length - 1; i >= 0; i--) {
if(digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newDigits = new int[digits.length + 1];
newDigits[0] = 1;
return newDigits;
}
}
Not bug free: 1) Wrong understand the digit position, significant bit is digits[0], 2) using undefined variable name n, n is the length of digits, remember to define variable first.
67. Add Binary
Question: Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Idea: Using a
StringBuilder
to maintain the result bit by bit, add the bit from the highest bit, and using a tag carry to save the carry result. pluse ASCII values of a and b in the corresponding position. Then add the sum result to StringBuilder , Finally, update the carry value and sum utill all the bits have been added. Finished while loop, check carry bit, if it is not 0, append it to the result, the reverse the result and save it to String.Time complex: O(N)
public class Solution {
public String addBinary(String a, String b) {
StringBuilder bf = new StringBuilder();
int aLength = a.length() - 1;
int bLength = b.length() - 1;
int carry = 0;
while(aLength >= 0 || bLength >= 0) {
int sum = 0;
if(aLength >= 0) {
sum += a.charAt(aLength--) - '0';
}
if(bLength >= 0) {
sum += b.charAt(bLength--) - '0';
}
sum += carry;
carry = sum / 2; // remember the sequence
sum = sum % 2;
bf.append(sum);
}
if(carry != 0) bf.append(carry);
return bf.reverse().toString();
}
}
Not bug free : 1) Index of a and b String, remember to check the length - 1, and while loop check condition is aLength >= 0 or bLength >= 0 2) finally update sum and carry, first update carry then update sum, because the sum will be cover. 3) Out of while loop, remember to check carry again.
228. Summary Ranges
Question: Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
Idea: Using a ArrayList save the result, Force brute traverse the array, save the first value of each loop, check the current value whether equals to its previous value plus one, if it is, increase the index. Finally, check current value with the saved first value. if they are the same, save the value as this range values, otherwise. save the first value + "->" + current values.
Time complex: O(N)
public class Solution {
public List<String> summaryRanges(int[] nums) {
ArrayList<String> result = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
int start = nums[i];
while(i < nums.length - 1 && nums[i+1] - nums[i] == 1) {
i++;
}
if(start == nums[i]) {
result.add(start + "");
} else {
result.add(start + "->" + nums[i]);
}
}
return result;
}
}
Not bug free: 1) Do not consider to complex. traversal the array from index 0 and the boundary condition is nums.length -1 2) finally check save previous value with current array value whether is the same start == nums[i]
, where the nums[i] is not continuous with it previous.
189. Rotate Array
Question: Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]
Idea: 1) Using extra space to save the result and then copy the result back to nums 2) reverse the array three times. First reverse the whole array, and according k divide the array into two parts, reverse the two part separately.
// extra space
public void rotate(int[] nums, int k) {
int[] result = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
result[(i + k) % nums.length] = nums[i];
}
for(int i = 0; i < nums.length; i++) {
nums[i] = result[i];
}
}
// O(1) space and O(n) time complex
public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
while(start <= end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
Not bug free: 1) reverse verstion: k can be more than nums.length, remember to mod nums.length; 2) reverse two part, one part have k number element, so the index remember to be k - 1; 3) extra space version: know how to copy a array, result[(i + k) % nums.length] = nums[i]
finding the relationship between nums and results.
27. Remove Element
Question: Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Idea: Finding the given value, and just cover the value with the following values in the array. So copy all the non-given values into the array from 0 one by one. eg: 0 1 2 0 4 5 6(0) -> 1 2 3 4 5 6
Time complex: O(N)
public int removeElement(int[] nums, int val) {
int index = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != val) {
nums[index] = nums[i];
index++;
}
}
return index;
}
Bug free for this idea. But the tag show two pointer did not figure out, My idea is move all the given value into behand the array using two pointer. !!! (Should figure out)
26. Remove Duplicates from Sorted Array
Question: Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
Idea: (Two pointer) one pointer i indicate the result save position in the array and show the current appeared values, the other pointer to find the difference value and save it to
nums[i + 1]
Time complex: O(n)
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int i = 0;
int j = 0;
int index = 0;
while(j < nums.length) {
j++;
while(j < nums.length && nums[i] == nums[j]) {
j++; // break means nums[j] is a new value
}
nums[index++] = nums[i];
i = j;
}
return index;
}
}
Not bug free: 1) if(nums == null || nums.length == 0)
remember to consider the inference of position || consider the condition on left or on right, put the more strict condition on left. 2) The same as (j < nums.length && nums[i] == nums[j]
3) Always considers i++. use first and then plus one
1. Two Sum
Question: Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Idea: 1) force brute search, two for loop to find whether two values sum is target or not. Time complex: O(N2), space complex is O(1)
2) Using hashMap to save index and value in pairs. keep value as key and index as values. Time complex: O(N) and space complex: O(N)
public int[] twoSum(int[] nums, int target) {
// force brute research (n2)
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
Bug free !!!! Good job.
public int[] twoSum(int[] nums, int target) {
// hashTable O(N)
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.get(target - nums[i]) != null ) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return null;
}
Not bug free: when defince hashMap remember to indicate the Type of its key and value. HashMap<Integer, Integer> map = new HashMap<>();
I forgot indicate HashMap<Integer, Integer>.
118. Pascal's Triangle My Submissions Question
Question: Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]]
Idea 1: Using extra space, use a prev arrayList to save the previous line, and a level represents current live of pascal's triangle, using the prev line to update the level line, then add level line into result.
Time complex: O(N2)
Space complex: O(N)
// extra space
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(numRows == 0) return result;
ArrayList<Integer> prev = new ArrayList<Integer>();
prev.add(1);
result.add(prev);
for(int i = 2; i <= numRows; i++) {
ArrayList<Integer> level = new ArrayList<Integer>();
for(int j = 0; j < i; j++) {
if(j == 0 || (j == i - 1)) {
level.add(1);
} else {
level.add(prev.get(j) + prev.get(j - 1));
}
}
result.add(level);
prev = level;
}
return result;
}
}
Not bug free : 1) using level.set(j, 1), right: level.add(1);
, know the difference between set() and add(), when the arrayList exists, then use set(index, value) to replace the original position values. But add() means to append a value in the arrayList, the original position have no values.
Idea 2: Using a arrayList to update each row, and then add the row into result two dimension array.
Time complex: O(N2)
Space complex: O(N)
public List<List<Integer>> generate(int numRows){
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> row = new ArrayList<Integer>();
for(int i = 0; i < numRows; i++) {
row.add(0, 1); // from row beginning insert a 1, row has numRows 1
for(int j = 1; j < row.size() - 1; j++) {
row.set(j, row.get(j) + row.get(j + 1)); //update j position values
}
result.add(new ArrayList<Integer>(row)); // row do not been erased
}
return result;
}
119. Pascal's Triangle II
Question: Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Idea 1: Using extra space to save the temp arrayList values, then update the result according the previous line (temp arryLsit)
Time complex: O(N2)
Space complex: O(N)
public class Solution {
public List<Integer> getRow(int rowIndex) {
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(1);
for(int i = 1; i <= rowIndex; i++) {
ArrayList temp = new ArrayList<Integer>();
for(int j = 0; j <= i; j++) {
if(j == 0 || j == i) {
temp.add(1);
} else {
temp.add(result.get(j) + result.get(j - 1));
}
}
result = temp;
}
return result;
}
}
Idea 2: No extra space, just using a arrayList to update the element in the array from index 1 to a.size() - 1, each time, insert a 1 at the beginning, then replace the following values one by one.
Time complex: O(N2)
Space complex: O(N)
public class Solution {
public List<Integer> getRow(int rowIndex) {
ArrayList<Integer> row = new ArrayList<Integer>();
for(int i = 0; i <= rowIndex; i++) {
row.add(0,1);
for(int j = 1; j < row.size() - 1; j++) {
row.set(j, row.get(j) + row.get(j+1));
}
}
return row;
}
}
Bug: The same with pascal's triangle | , discriminate add() and set()
283. Move Zeroes
Question: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Idea 1: moving non-zero value to the beginning of the array, and then insert the result of the array with zero 0.
Time complex: O(N)
public class Solution {
public void moveZeroes(int[] nums) {
int index = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != 0) {
nums[index++] = nums[i];
}
}
while(index < nums.length) {
nums[index++] = 0;
}
}
}
Bug free! Good job.
Idea 2: swap 0 with following non-zero value
public void moveZeroes(int[] nums) {
int zeroPosition = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 0) {
zeroPosition++;
continue; // ignore the following exchange
}
int temp = nums[i - zeroPosition];
nums[i - zeroPosition] = nums[i];
nums[i] = temp;
}
}
Bug free! Good job.
88. Merge Sorted Array
Question: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
Idea: Compare two array values from the end of array, move the bigger one into nums1 for m + n - 1 to fill with the big value. Unitl all the element in the two array have been move to nums1. If m > n, the left m in nums1 need not to move, they are already in the right position. If left n, move all left n values from nums2 into nums1.
Time complex: O(N)
Space complex: O(1)
public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
while(m > 0 && n > 0) {
if(nums1[m - 1] > nums2[n - 1]) {
nums1[m + n - 1] = nums1[m - 1];
m--;
} else {
nums1[m + n - 1] = nums2[n - 1];
n--;
}
}
while(n > 0) {
nums1[m + n - 1] = nums2[n - 1];
n--;
}
}
}
Not bug free: 1) Notice the index of nums1 and nums2, the last element in nums1 is nums1[m - 1] and the last element of nums2[n - 1]. 2) when move one element. remember to update the cooperate index.
169. Majority Element
Question: Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Idea: using a count to indicate the major, save the first one value as major, then if it is the same value, increase count. if it is different value. decrease the count, when count decrease to 0, update mojor value. Finally return the major value. This problem do not consider the test case do not have the majority element. This algorithm, when count bigger than 0 means than major element have appeared more than n/2 times.
public class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int major = 0;
for(int i = 0; i < nums.length; i++) {
if(count == 0) {
count++;
major = nums[i];
} else if(nums[i] == major){
count++;
} else {
count--;
}
}
// System.out.println(count);
return major; // once count bigger then 0, means that the major appear more than n/2 times
// if(count > 0) {
// return major;
// } else {
// return 0;
// }
}
}
Not bug free: 1) if count == 0, update major value, when nums[i] is major, increase count, otherwise, when nums[i] is not equals to major, decrease count. Finally when count bigger than 0, major is the result, otherwise, there is no majority elements exsits.
Medium
220. Contains Duplicate III
Question: Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
补充知识点:Binary search tree:
function | Array(unsorted) | LinkedList | Array(sorted) | BST |
---|---|---|---|---|
search(x) | O(N) | O(N) | O(log(n)) | O(log(n)) |
insert(x) | 0(1) | O(1) | O(N) | O(log(n)) |
remove(x) | O(N) | O(N) | O(N) | O(log(n)) |
Binary search tree is a binary tree in which for each node, value of all the nodes in left subtree is lesser or equal and value of all the nodes in right subtree is greater. (balance and unbalance, if unbalance, it is the woset case, O(N(log(n))))
TreeSet : have two method, foor() and ceiling();
Idea : finding the boundary nums[i] - t and nums[i] + t, save the values in the boundary into a set, maintain the index distance is k, then maintain the index distance k, traverse the the set to find nums[i] whether is within the boundary.
Time complex: N log (K) K is the sub set size, N is length of the array.
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> set = new TreeSet<>();
for(int i = 0; i < nums.length; i++) {
Integer floor = set.floor(nums[i] + t);
Integer ceil = set.ceiling(nums[i] - t);
if((floor != null && floor >= nums[i]) || (ceil != null && ceil <= nums[i])) {
return true;
}
set.add(nums[i]);
if(i >= k) {
set.remove(nums[i - k]);
}
}
return false;
}
}