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. MVC TO LINQ

    // // GET: /Home/ TestTryEntities Db = new TestTryEntities(); public ActionResult Index() { return V ...

  2. MongoDB的一些用法(转藏)

    MongoDB是目前工作中经常使用到的NoSQL数据库. 本博客只记录相关理论知识和技巧,涉及到实践的部分都会单开Blog来记录实践过程. ------------------------------ ...

  3. python 调用 bash (python 调用linux命令)

    原文这里有显示地址:http://zhou123.blog.51cto.com/4355617/1312791 现在摘取一部分: 这里介绍一下python执行shell命令的四种方法: 1.os模块中 ...

  4. vsftp FTP服务器 server settings , and add different users

    建议阅读知识:http://linux.vbird.org/linux_basic/0210filepermission.php  这是关于档案权限,用户,组等的问题.介绍的很有意思. 1. Inst ...

  5. 在C中判断变量存储类型(字符常量/数组/动态变量)

    在C中判断变量存储类型(字符常量/数组/动态变量) 在chinaunix论坛上有人问到关于变量存府类型的问题,我觉得可以写个测试代码加深大家对内存使用和布局的理解.下面我把原问题及处理办法贴出来,限供 ...

  6. aix上使用裸设备安装oracle10g数据库

    一.检查系统信息 [root@aix222 /]# oslevel -r 5300-08 [root@aix222 /]# prtconf | grep -i mem Memory Size: 190 ...

  7. 命令版本git 分支篇-----不断更新中

    最近应用开发的过程中出现了一个小问题,顺便记录一下原因和方法--命令版本 开发中想看看过去某个版本的代码,我们先查看log git log commit f224a720b8192165a4e70f2 ...

  8. github 自学文档 希望可以给初学的人一些帮助

    一 .git的安装 windows下面的安装:https://git-for-windows.github.io  从这里下载完全无脑安装. 安装完成后,在开始菜单里找到"Git" ...

  9. Elasticsearch 2.3 (ELK)Geo_point绘图、日志Date时间获取实例

    前言:本文源于天天是雾霾新闻,我想利用kibana画一下一线城市雾霾图,希望对想利用经纬度在kibana绘图和获取日志本身时间绘图的同学有所帮助.有什么疑问或者纠错,可以给我发邮件 一.数据准备 为了 ...

  10. nodejs,http,get,post,请求

    本文源于实践及其部分网络搜索: 其实大部分,官方都有介绍... 官方参考链接:https://nodejs.org/api/http.html var http = require('http'); ...