General

Intersection of 2 sorted arrays

while(i < a.size && j < b.size()){
  if(a.get(i) == b.get(j) && (i == 0 || a.get(i) != a.get(i-1))){
    sortedList.add(a.get(i));
    i++;
    j++;
  }
}

Merge 2 sorted arrays

The first list has enough space for list 2

while ( m >= 0 && n >= 0 ){
  a.set(writeIndex--, a.get(m) > b.get(n) ? a.get(m--): b.get(n--));
}
while ( n >= 0){
  a.set(writeIndex--, b.get(n--));
}

K-largest element

  • Sort and find k, O(nlogn)

  • min heap or max heap, O(nlogk)

  • like quicksort, average O(n), worst O(n^2)

    1. use partition in quicksort, find the pivot == k

    2. If find k largest, k - size + 1

  • Hint: quicksort 中,pivot 左邊的數字都小於等於nums[pivot]

280. Wiggle Sort

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

324. Wiggle Sort II

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

Last updated

Was this helpful?