策略 & 注意点
array 在内存里是连续存储的,意味着 immutable length 和 no holes allowed。带来的优点是支持随机访问,缺点是当 resize array 的时候需要 copy 原有的所有元素,当删除一个不在末尾的元素时,又要 shift 很多元素。
数组最需要注意的:
- length 问题,最后一个数 array[len(array)-1]
- 指针问题,deepcopy or shallowcopy,对原数组进行多次变形并需纪录每次结果时,要注意 deepcopy 而不是存指针。res.append(list(nums)),如 permutation 这种题。
- 可以用虚拟边界
- 利用 array 的 index 可以做很多事情(利用 nums[i] 和 nums[nums[i]])。如 Find the Duplicate Number,把 array 变成 linkedlist,或者
Efficiency
Insertion at back: O(1)
Insertion at front: O(n)
Insertion in middle: O(n)
Searching (using linear search): O(n)
Deletion: O(n)
Access to an element with its index: O(1)
python lists
|
|
Java Arrays
在 java 里,array 有一个方法,clone(),属于 shallow copy。有一个 immutable field,length。
Java Arrays 好用的方法
outputs
Java List
|
|
Java 7,ArrayList 用的是 doubling-up policy。也就是说,假定 ArrayList 的初始 capacity 为 4,那么加入第 n(n<=4) 个元素的 running time 是 1,而加入第 5 个 item 时,running time 是 5 而不是 1,因为要重新创建一个 double-size list 再把原来的元素 copy 进去。同样的,加入第 9 个元素时的 running time 是 9 而不是 1。用 amortized 的方法可以发现 add(E e) 的操作的 running time 是一个常数,也就是 O(1)。
例题
66. Plus One
Problem
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Similar problems (M) Multiply Strings (E) Add Binary (M) Add Two Numbers (M) Plus One Linked List
2.445. Add Two Numbers 369. Plus One Linked List
43. Multiply Strings
Solution
|
|
67. Add Binary
Problem
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
Solution
|
|
228. Summary Ranges
Problem
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”].
Solution
|
|
360. Sort Transformed Array
Problem
Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array.
The returned array must be in sorted order.
Expected time complexity: O(n)
Example:
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
Solution
|
|
346. Moving Average from Data Stream
Problem
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3
Solution
|
|
75. Sort Colors
subarray 问题
Problem
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.
Note:
You are not suppose to use the library’s sort function for this problem.
Solution
|
|
53. Maximum Subarray
Problem
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Solution
|
|
Snapchat 面经
Problem
Returns unsorted part of an array.
For example, input -> [1,2,5,7,6,4,9], output -> [5,7,6,4]
Solution
|
|
Finding sum of Absolute Difference of Every pair of integer from an array
Problem
Given an array, find the sum of the absolute difference of every pair of integers.
For example: Given a[]= {2, 3, 5, 7 };
output would be (3-2) + (5-2) + (7-2) + (5-3) + (7-3) + (7-5) = 17.
It must be done better than O(n^2).
The original array isn’t necessarily sorted.
Solution
|
|
11. Container With Most Water
Problem
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
Solution
|
|
84. Largest Rectangle in Histogram
Problem
Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
Solution
|
|
463. Island Perimeter
Problem
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.
Example:
Solution
|
|
448. Find All Numbers Disappeared in an Array
Problem
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Tags: Array
Similar Problems: (H) First Missing Positive (M) Find All Duplicates in an Array
Solution
|
|
442. Find All Duplicates in an Array
Problem
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Tags: Array
Similar Problems: (E) Find All Numbers Disappeared in an Array
Solution
|
|
41. First Missing Positive
Problem
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Tags: Array
Similar Problems: (M) Missing Number (H) Find the Duplicate Number (E) Find All Numbers Disappeared in an Array
Solution
|
|
287. Find the Duplicate Number
Problem
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.
Tags: Binary Search Array Two Pointers
Similar Problems: (H) First Missing Positive (E) Single Number (M) Linked List Cycle II (M) Missing Number
Solution
|
|