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:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. 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;
}
}

Leetcode 解题报告的更多相关文章

  1. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  2. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  3. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  4. leetCode解题报告5道题(六)

    题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest s ...

  5. LeetCode解题报告—— Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  6. LeetCode解题报告—— Search in Rotated Sorted Array & Search for a Range & Valid Sudoku

    1. Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated(轮流,循环) at so ...

  7. LeetCode解题报告—— 2 Keys Keyboard & Longest Palindromic Substring & ZigZag Conversion

    1. Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You ...

  8. LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum

    1. 1-bit and 2-bit Characters We have two special characters. The first character can be represented ...

  9. LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结

    前言: 这几天在做LeetCode 里面有2sum, 3sum(closest), 4sum等问题, 这类问题是典型的递归思路解题.该这类问题的关键在于,在进行求和求解前,要先排序Arrays.sor ...

  10. leetcode解题报告(13):K-diff Pairs in an Array

    描述 Given an array of integers and an integer k, you need to find the number of unique k-diff pairs i ...

随机推荐

  1. IOS学习之路(代码实现自动布局)

    1.将一个试图放置在其父视图的中央位置,使用限制条件. 2.创建两个限制条件:一个是将目标视图的 center.x 位置排列在其父视图的 center.x 位置,并且另外一个是将目标视图的 cente ...

  2. 基于Redis的CustomerSessionProvider(一)

    CustomerSessionProvider需要实现SessionStateStoreProviderBase 在设计Redis Session Provider的时候,需要考虑 1.是否每个用户的 ...

  3. ORA-12520错误解决方法

    ORA-12520监听程序无法为请求的服务器类型找到可用的处理程序 以下不知道是不是解决方法的方法,因为我只重启下oracle服务就好了,并没进行任何修改 引用别人的文章: 1)数据库是专用服务器,但 ...

  4. ASP.NET MVC3开发-数据库篇之CodeFisrt开发(一)

    本文讲述了在ASP.NET MVC3开发中M层使用Code Fisrt如何进行开发,由于作者对ASP.NET MVC3的学习不是很深,所以写的都是些基本的内容(写的如有不正确的地方请评论指正),适合初 ...

  5. 判断0-N之间出现1的次数

    Console.WriteLine("请输入截止数字?退出请输入y"); string input = Console.ReadLine(); int n = Convert.To ...

  6. 由IEnumerable和IEnumerator的延伸

    相信大家在学习c#的时候,经常会看到IEnumerable.IEnumerator这样的接口或返回类型,在写代码时经常会对数组或List集合进行遍历.那IEnumerable和IEnumerator是 ...

  7. tag标签记录

    看到项目代码中有一个自定义的tag标签,想起以前自己写过的标签,竟然忘记的差不多了,手一痒,自己写个简单的tag标签,回顾一下历史知识 首先建一个servlet工程,然后写个index.jsp,项目跑 ...

  8. bios中断向量表

  9. 做个简单的Redis监控(源码分享)

    Redis监控 Redis 是目前应用广泛的NoSQL,我做的项目中大部分都是与Redis打交道,发现身边的朋友也更多人在用,相对于memcached 来说,它的优势也确实是可圈可点.在随着业务,数据 ...

  10. Chrome使用小技巧-多用户登录、直接打开隐身模式窗口

    在开发过程中,有时候需要打开2个chrome,各自登录一个账号来做测试,正常情况下由于同一用户下的chrome共享cookies的原因,是没办法登录2个账号的. 这种情况,可以找到chrome图标,点 ...