Intersection of Two Arrays
Question
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Analysis
两个HashSet分别用于找Intersection和存储不重复结果
时间复杂度 :O(n)
Code
|
|
Intersection of Two Arrays II
Question
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1‘s size is small compared to nums2‘s size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Analysis
- 将两个数组排序之后利用两个指针跟踪两个数组的元素进行比较,相等时加入结果,否则较小的数字方的指针向下移动。
- 或者不排序,利用HashMap来记录每个元素的出现次数,每遇到重复便将次数-1
Answer To Third Follow Up Question
- 假如只有nums2不能放入内存中,则将nums1放入HashMap中,每次从disk中读取恰巧可以放入内存中大小的数据,记录intersection
- 假如nums1 与 nums2 均不能放入内存中,则对其分别利用外排(external sort)进行排序,则每次读取比如2G的数据(内存中可以放的下的大小),利用Two Pointers找到intersection,循环执行这个步骤直至没有数据可比较。
Code
|
|
Shorter Version
|
|
H-Index
桶排序思想
Valid Anagram
Question
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Analysis
利用int数组记录每个字母出现的次数,第一个串遍历的过程中++,第二个串遍历的过程中- - ,最后判断是否数组中所有的元素均为0.
Code
|
|
Largest Number
Sort List
Question
Sort a linked list in O(n log n) time using constant space complexity.
Analysis
时间复杂度 O(n) 空间复杂度 O(logn)
调用了log(length)次Merge
Code
|
|
Insertion Sort List || Sort List
Sort Colors
Question
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Analysis
在五个月内做了三遍的题还是一直在错,基本思想是red,blue两个指针,将元素0,2分别交换到数组首和末尾。
- 交换的循环条件是i小于等于blue的指针
- 由于停止的条件是i<=blue,所以应该先交换blue,后交换red
Code
|
|
Insert Interval||Merge Intervals
注意所给区间均为闭区间,所以在控制边界调节时(合并等)在等号成立的时候也需要执行。