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. js闭包(转)

    一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变量. Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量 ...

  2. 运用Unity实现AOP拦截器

    运用Unity实现AOP拦截器[结合异常记录实例] 本篇文章将通过Unity实现Aop异常记录功能:有关Unity依赖注入可以看前两篇文章: 1:运用Unity实现依赖注入[结合简单三层实例] 2:运 ...

  3. TortoiseSVN使用方法 安装和配置

    TortoiseSVN使用方法   安装和配置 TortoiseSVN的下载地址为 http://tortoisesvn.net/downloads.html 有32位和64位的版本,一定要根据自己的 ...

  4. iphone手机用wireshark抓包

    ios连上电脑 查看udid. 启动虚拟接口 rvictl -s 7e65eeaa55a1e43dbdfb44a02f9871f1f304043e 打开mac权限 sudo chmod 644 /de ...

  5. CodeFirst 初恋

    CodeFirst 初恋 原著:Prorgamming Entity Framework Entitywork Code First 大家好! 我是AaronYang,这本书我也挺喜欢的,看了一半了, ...

  6. Eclipse RCP /Plugin移除Search对话框

    RCP:如何移除Search对话框中不需要的项 2013-08-18 22:31 by Binhua Liu, 231 阅读, 0 评论, 收藏, 编辑 前言 很久没写文章了,准备写一系列关于Ecli ...

  7. CentOS中安装Python-PIP

    wget http://pypi.python.org/packages/source/p/pip/pip-1.0.2.tar.gz tar zxf pip-1.0.2.tar.gz cd pip-1 ...

  8. 用T4消除代码重复,对了,也错了

    用T4消除代码重复,对了,也错了 背景 我需要为int.long.float等这些数值类型写一些扩展方法,但是我发现他们不是一个继承体系,我的第一个思维就是需要为每个类型重复写一遍扩展方法,这让我觉得 ...

  9. ajax的分页查询(不刷新页面)

    既然是分页查询,那么就要有张数据很多的表,可以让它进行分页显示,用普通的方法进行分页查询必然是要刷新页面的,这里要实现不刷新页面进行分页显示数据,就要用到ajax方式.进行编写代码 (1)先写个显示数 ...

  10. CSS预处理器的对比 — Sass、Less和Stylus

    本文根据Johnathan Croom的<sass vs. less vs. stylus: Preprocessor Shootout>所译,整个译文带有我们自己的理解与思想,如果译得不 ...