347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
思路:算法上没有什么新颖的地方,主要是数据结构和相应函数的使用。
先用Map 来存储数值和数值出现的次数,再对map进行排序,排序的时候按照value的值排序,最后输出后k个值。
需要注意的是排序的方法,这里用到了Collections.sort()函数的其中一种方式,就是自定义compare函数,来实现自己想要的函数。
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer,Integer> m = new HashMap<Integer,Integer>();
List<Integer> res = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) {
if (m.containsKey(nums[i])) {
m.put(nums[i], m.get(nums[i])+1);
} else {
m.put(nums[i], 1);
}
}
List<Map.Entry<Integer, Integer>> l = new ArrayList<Map.Entry<Integer, Integer>>(m.entrySet());
Collections.sort(l, new Comparator<Map.Entry<Integer,Integer>>() {
public int compare(Map.Entry<Integer, Integer> me1, Map.Entry<Integer, Integer> me2) {
return me1.getValue().compareTo(me2.getValue());
}
});
int size = m.size();
for (int i = 0; i < k; i++) {
res.add(l.get(size - 1 - i).getKey());
}
return res;
}
96. Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
思路:考虑根节点的可能性,有n种,对于每一个数字i(1<=i<=n)为根节点时,所对应的BST的数量是 左子树的数量*右子树的数量。
左右子树的节点数量之和为i-1,并且分别是从0~i-1 和i-1~0对应变化。用dp[i]表示有i个节点的BST的数量,以j表示左子树节点数量,初始条件为dp[0] = 1,则有
for j: 0~i-1
dp[i] += dp[j]*dp[i-1-j];
public int numTrees(int n) {
int[] dp = new int[n+1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0;j <= i-1; j++) {
dp[i] += dp[j] * dp[i - 1 - j];
}
}
return dp[n];
}
338. Counting Bits --20160518
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Hint:
- You should make use of what you have produced already.
- Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
- Or does the odd/even status of the number help you in calculating the number of 1s?
思路:这是一个找规律的题,前后数字的1的个数是有增长的规律的。在稿纸上写出来就可以清晰地看到,这里就不赘述,直接上代码。
public class S338 {
public int[] countBits(int num) {
int[] count = new int[num+1];
int k = 0;
for (int i = 1; i <= num;) {
int temp = (int)Math.pow(2, k);
for (int j = 0; j < temp; j++) {
count[i] = count[i - temp] + 1;
i++;
if(i > num) {
break;
}
}
k++;
}
return count;
}
}