Maintain a min-heap with size = k, to collect the result. //Find K minimum values from an unsorted array //Implement Min-Heap public int[] findKMax(int[] arr, int k){ if(arr == null || arr.length == 0) return null; int[] result = new int[k]; for(int…
这是我在逛 Stack Overflow 时遇见的一个高分问题:Why is processing a sorted array faster than an unsorted array?,我觉得这是一个非常好的用来讲分支预测(Branch Prediction)的例子,分享给大家看看 一.问题引入 先看这个代码: #include <algorithm> #include <ctime> #include <iostream> #include <stdint…
(referrence: GeeksforGeeks, Kth Largest Element in Array) This is a common algorithm problem appearing in interviews. There are four basic solutions. Solution 1 -- Sort First A Simple Solution is to sort the given array using a O(n log n) sorting alg…
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. Example 1: Given nums = [1, -1, 5, -2, 3], k = 3,return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the…
What is Branch Prediction? Consider a railroad junction: Image by Mecanismo, via Wikimedia Commons. Used under the CC-By-SA 3.0 license. Now for the sake of argument, suppose this is back in the 1800s - before long distance or radio communication. Yo…
[本文链接] http://www.cnblogs.com/hellogiser/p/Longest-Consecutive-Sequence-in-an-Unsorted-Array.html [题目] 一个无序自然数数组,比如[100,2,1,3]求在0(n)时间复杂度内求出最大的连续自然数个数:输出应该是3 [分析] 方法一:排序可以采用一些排序方法比如基数排序.桶排序.记数排序等先进行排序.然后遍历一遍所有元素即可.当前这些排序有一些限制条件的. 方法二:维持一个hash表维持一个has…
http://www.geeksforgeeks.org/find-the-two-numbers-with-odd-occurences-in-an-unsorted-array/ #include <iostream> #include <vector> #include <algorithm> #include <queue> #include <stack> #include <string> #include <fst…
Maximum Gap Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array a…
Maximum Gap Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array a…
Maximum Gap Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Return 0 if the array contains less than 2 elements. Example 1: Input: [3,6,9,1] Output: 3 Explanation: The sorted form of the array…