1. 程式人生 > >九章演算法7:Array & Numbers

九章演算法7:Array & Numbers

九章演算法7:Array & Numbers

Merge two sorted array

Given two sorted integer arrays A and B, merge B into A as one sorted array.
A = [1, 2, 3, empty, empty], B = [4, 5]
After merge, A will be filled as [1, 2, 3, 4, 5]

我的第一反應,直接insert啊…naive啊…
老師說:陣列問題, 最好不要進行陣列的整體移動的操作.
所以我們這次不誰小誰出列,我們進行誰大誰出列,從後面進行操作~
遇到新題的思維方法:

   1.如果比較直接,如上面的 merge two sorted array, 但是好像直接做又不是那麼特別好,可以考慮在直接的第一眼思維得出的解法上面稍加變動, 比如: 從左到右變成從右到左, 最小變最大, 一個指標變倆....
   2.如果不是很直接的,考慮和之前哪道題像親戚.比如合併k個數組就可以聯想道合併2個數組,能不能在親戚題的解法上進行改進解決這道題.
   3.如果不直接又"舉目無親",根據題目的敘述看神馬學過的演算法或者資料結構貌似可以用上的,比如:求最大,最小,方案數以及可行性的想動態規劃,k個數求最小用heap
   4.如果還是想不出來,試試其它的能扯上的資料結構和演算法....還是不行就硬想吧...

Median of a two sorted array

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays.

Given A=[1,2,3,4,5,6] and B=[2,3,4,5], the median is 3.5.

Given A=[1,2,3] and B=[4,5], the median is 3.

線上性時間複雜度之後, 還有一種更有的logn的解法.
logn用的是二分法, 二分法的本質是, 通過O(1)的時間把一個n的問題變為n

2的問題.

這道題可以理解為一個更廣泛的問題, 在logk的時間裡找到第k大…諸如此類的有找到median, 找第1大,第2大…第k大的問題.
這道題裡面: k=m+n2
這裡面的演算法是這樣的:

1.首先我們想用二分法找到第k個數,即用logk的時間找到第k大的數,這道題稍微難理解的一點,我個人認為是如下:

正常的二分法是經過一次運算,有一半的資料量被篩除淘汰了,比如一棵二叉樹上查詢,你往下左走一步,右邊的那顆子樹就出局了;往右走一步,左面那個子樹的資料就都不要了;

而這道題稍微拐一點彎的地方就在於,資料量本身直觀的不是k,而且好像扔掉了k2,剩下的資料量跟二分之一有關,但好像也不是一半,然後稀裡糊塗的就有點繞懵了…

我們換一個角度理解這道題運用的二分法思想,假設A,B兩個排過序的陣列都無限長,那麼我們想找到兩個陣列的第k大,備選的是A的前k大的數和B的前k大的數,你也不知道在哪個裡,不過肯定就這兩個裡面跑不了.我們通過一次O(1)的運算,排除了k2個肯定不是第k大的,由找第k大的元素變成找第(k-k2)即k2大的,所以搜尋範圍變成了在A剩下的數裡面前k2大的,和B剩下的裡面k2大的. 總共的篩選範圍縮小了一半, oh yeah!

我覺得我用這種方法捋清了一點,但是說完感覺沒什麼卵用…

2.具體程式的邏輯如下:

 對於一個長度為n的已排序數列a,若n為奇數,中位數為a[n / 2 + 1] , 若n為偶數,則中位數(a[n / 2] + a[n / 2 + 1]) / 2
如果我們可以在兩個數列中求出第K小的元素,便可以解決該問題

不妨設數列A元素個數為n,數列B元素個數為m,各自升序排序,求第k小元素
取A[k / 2] B[k / 2] 比較, 

如果 A[k / 2] > B[k / 2] 那麼,所求的元素必然不在B的前k / 2個元素中(證明反證法)

k - k / 2小元素,於是得到了資料規模變小的同類問題,遞迴解決

如果 k / 2 大於某數列個數,所求元素必然不在另一數列的前k / 2個元素中,同上操作就好。  

賣股票

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Given an example [3,2,3,1,2], return 1

Maximum subarray

Given an array of integers, find a contiguous subarray which has the largest sum.
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

對於所有位置n, 求前n個數的和, 然後每個數減前面最小的, 搞定啦~

這兩道題就像孫紅雷和牛頭梗,分開看的時候有點分馬牛不相及,放一起仔細一看就是好兄弟啊~

maximum subarray II

Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.

For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3] and [2, -1, 2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.

每個位置砍一刀,左邊做一次上道題,右邊再做一次,得解~

Subarray sum

Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.

Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

加個hashtable, 搞定~

Subarray sum closest

Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

Given [-3, 1, 1, -3, 5], return [0, 2], [1, 3], [1, 1], [2, 2] or [0, 4].

排個序,具體寫題的時候再補充.

寫程式的主體事項

分好模組,每個函式模組就幹一件事情,不要把所有的東西堆在一起,容易出問題還不易讀懂.

Two sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.

You may assume that each input would have exactly one solution

numbers=[2, 7, 11, 15], target=9
return [1, 2]

O(n)時間O(n) 空間的很容易達到.
O(1)空間的時候,時間就不再是O(n)了,而是O(nlogn)了

前後兩個指標head和tail, 如果相加大於target, tail左移,否則head右移.

題外話:二分法也是兩根指標:進行了一次操作,把一根指到了中間而已

3 Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Notice

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)

The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:

(-1, 0, 1)
(-1, -1, 2)

排序一下, for a這個最小的,找b+c = -a的

Partition array

Given an array nums of integers and an int k, partition the array (i.e move the elements in “nums”) such that:

All elements < k are moved to the left
All elements >= k are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k.

Notice

You should do really partition in array nums instead of just counting the numbers of integers smaller than k.

If all elements in nums are smaller than k, then return nums.length

If nums = [3,2,2,1] and k=2, a valid answer is 1.
大於的右移,小於的左移

Sort Letters by Case

Given a string which contains only letters. Sort it by lower case first and upper case second.

Notice

It’s NOT necessary to keep the original order of lower-case letters and upper case letters.

For “abAcD”, a reasonable answer is “acbAD”

這道題的注意點是, swap是一個不能保證元素之間相對位置的操作,各種sort是否stable如下

 1.quick sort 不穩定
 2.merge sort 穩定
 3.各種O(n^2)的演算法:冒泡,選擇, 插入等   穩定
 4.heap sort 不穩定

這道題的總結是,不知道啥是選擇和插入排序…回頭看看..

Sort colors

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.

Notice

You are not suppose to use the library’s sort function for this problem.
You should do it in-place (sort numbers in the original array).

Given [1, 0, 1, 2], sort it in-place to [0, 1, 1, 2].

  1. counting sort 數數有多少個0, 多少個1, 多少個2
  2. 先partition等於0 和不等於0 的 分兩部分,然後再把不等於0 的那部分再partition

Sort Colors II

Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, … k.

Notice

You are not suppose to use the library’s sort function for this problem.

Given colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4].

陣列排序…尼瑪…直接的我難以置信…