LeetCode(四)
Find Kth Largest Number
public class Solution {
public int findKthLargest(int[] nums, int k) {
return findK(nums,nums.length - k,0,nums.length-1);
}
private int findK(int[] nums,int k, int start, int end){
int parti = nums[start],i=start,m=start;
for(int j=start+1;j<=end;j++){
if(nums[j]>parti)
continue;
if(nums[j]<=parti){
swap(nums,++i,j);
if(nums[j] != parti)
swap(nums,m++,i);
}
}
if(k>=m && k<=i)
return nums[k];
else if(k < m)
return findK(nums,k,start,m-1);
else
return findK(nums,k,i+1,end);
}
private void swap(int[] nums, int a, int b){
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}
Count Primes
public class Solution {
public int countPrimes(int n) {
int res = 0;
boolean[] used = new boolean[n];
for (int i = 2; i <= Math.sqrt(n); i++) {
if (!used[i - 1]) {
int temp = i * i;
while (temp < n) {
used[temp - 1] = true;
temp += i;
}
}
}
for (int i = 2; i < n; i++) {
if (!used[i - 1]) {
res++;
}
}
return res;
}
}
Number of 1bits
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
n = n & (n-1);
count++;
}
return count;
}
}
Largest Number
public class Solution {
public String largestNumber(int[] num) {
StringBuilder res = new StringBuilder();
if (num == null || num.length == 0)
return null;
//conver Integer to string
String[] nums = new String[num.length];
for (int i = 0; i < num.length; i++)
nums[i] = Integer.toString(num[i]);
//Define comparator
Comparator<String> comp = new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return (o1+o2).compareTo(o2+o1);
}
};
Arrays.sort(nums, comp);
//The new number should not start with 0 unless it is 0
if (nums[nums.length-1].equals("0"))
return "0";
for (int i = nums.length-1; i >= 0; i--)
{
res.append(nums[i]);
}
return res.toString();
}
}
Major Element
public class Solution {
public int majorityElement(int[] nums) {
// moore's voting algorithm
// find candidate element
if (nums.length == 1) return nums[0];
int majorityIndex = 0, count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[majorityIndex]) count++;
else count--;
if (count == 0) {
majorityIndex = i;
count = 1;
}
}
// check if candidate is the majority element
return nums[majorityIndex];
}
}
Reverse Words in a String
public class Solution {
public char[] reverse(char[] arr, int i, int j) {
while (i < j) {
char tmp = arr[i];
arr[i++] = arr[j];
arr[j--] = tmp;
}
return arr;
}
public String reverseWords(String s) {
// reverse the whole string and convert to char array
char[] str = reverse(s.toCharArray(), 0, s.length()-1);
int start = 0, end = 0; // start and end positions of a current word
for (int i = 0; i < str.length; i++) {
if (str[i] != ' ') { // if the current char is letter
str[end++] = str[i]; // just move this letter to the next free pos
} else if (i > 0 && str[i-1] != ' ') { // if the first space after word
reverse(str, start, end-1); // reverse the word
str[end++] = ' '; // and put the space after it
start = end; // move start position further for the next word
}
}
reverse(str, start, end-1); // reverse the tail word if it's there
// here's an ugly return just because we need to return Java's String
// also as there could be spaces at the end of original string
// we need to consider redundant space we have put there before
return new String(str, 0, end > 0 && str[end-1] == ' ' ? end-1 : end);
}
}
Sqrt(x)
public class Solution {
public int mySqrt(int x) {
if (x == 0)
return 0;
int left = 1, right = x;
while (true) {
int mid = left + (right - left)/2;
if (mid > x/mid) {
right = mid - 1;
} else {
if (mid + 1 > x/(mid + 1))
return mid;
left = mid + 1;
}
}
}
}
pow(x,n)
public class Solution {
public double myPow(double x, int n) {
if(n==0) return 1;
if(x==0) return 0;
int sign = (x<0)?-1 : 1;
double tmpX = Math.abs(x);
int tmpN = Math.abs(n);
double pow1 = myPow(tmpX,tmpN/2);
double pow2;
if(tmpN%2 == 1){pow2 = pow1*tmpX;}
else pow2 = pow1;
double pow3;
pow3 = (tmpN%2==1)?pow1*pow2*sign:pow1*pow2;
return (n>0)?pow3:1/pow3;
}
}
Divide Two Integers
public class Solution {
public int divide(int dividend, int divisor) {
//Reduce the problem to positive long integer to make it easier.
//Use long to avoid integer overflow cases.
int sign = 1;
if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0))
sign = -1;
long ldividend = Math.abs((long) dividend);
long ldivisor = Math.abs((long) divisor);
//Take care the edge cases.
if (ldivisor == 0) return Integer.MAX_VALUE;
if ((ldividend == 0) || (ldividend < ldivisor)) return 0;
long lans = ldivide(ldividend, ldivisor);
int ans;
if (lans > Integer.MAX_VALUE){ //Handle overflow.
ans = (sign == 1)? Integer.MAX_VALUE : Integer.MIN_VALUE;
} else {
ans = (int) (sign * lans);
}
return ans;
}
private long ldivide(long ldividend, long ldivisor) {
// Recursion exit condition
if (ldividend < ldivisor) return 0;
// Find the largest multiple so that (divisor * multiple <= dividend),
// whereas we are moving with stride 1, 2, 4, 8, 16...2^n for performance reason.
// Think this as a binary search.
long sum = ldivisor;
long multiple = 1;
while ((sum+sum) <= ldividend) {
sum += sum;
multiple += multiple;
}
//Look for additional value for the multiple from the reminder (dividend - sum) recursively.
return multiple + ldivide(ldividend - sum, ldivisor);
}
}
Plus One
public class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for(int i=n-1; i>=0; i--) {
if(digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newNumber = new int [n+1];
newNumber[0] = 1;
return newNumber;
}
}
Add Binary
public class Solution {
public String addBinary(String a, String b) {
int lena = a.length();
int lenb = b.length();
int i =0, carry = 0;
String res = "";
while(i<lena || i<lenb || carry!=0){
int x = (i<lena) ? Character.getNumericValue(a.charAt(lena - 1 - i)) : 0;
int y = (i<lenb) ? Character.getNumericValue(b.charAt(lenb - 1 - i)) : 0;
res = (x + y + carry)%2 + res;
carry = (x + y + carry)/2;
i++;
}
return res;
}
}
LeetCode(四)的更多相关文章
- leetcode 四数之和
这里我们可以考虑将 n 数之和降低为一个数加上 n-1 数之和的问题.依次降低 ,最低是二数之和的问题 ,二数之和问题容易解决.主要在于从 n 到 n-1 的过程需要理解 :下列代码中前几个 if 是 ...
- day07整理(内置方法\循环判断)
目录 一.上节课回顾 (一)if判断 1.单分支结构 2.双分支结构 3.多分支结构 (二)for循环 1.for + break 2.for + continue 3.for循环嵌套 (三)robu ...
- [LeetCode] 4Sum II 四数之和之二
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such t ...
- [LeetCode] 4Sum 四数之和
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...
- Leetcode:LRUCache四个版本实现
题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...
- LeetCode 18. 4Sum (四数之和)
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...
- LeetCode第四天
leetcode 第四天 2018年1月4日 15.(628)Maximum Product of Three Numbers JAVA class Solution { public int max ...
- [LeetCode] 4 Keys Keyboard 四键的键盘
Imagine you have a special keyboard with the following keys: Key 1: (A): Print one 'A' on screen. Ke ...
- LeetCode算法题-Minimum Distance Between BST Nodes(Java实现-四种解法)
这是悦乐书的第314次更新,第335篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第183题(顺位题号是783).给定具有根节点值的二叉搜索树(BST),返回树中任何两个 ...
随机推荐
- jquery datatables双击,获取行号。
function dbClickDatatables(rows) { $("#@(Perfix)tbData tbody tr").dblclick(function(e){ de ...
- CSS id 选择器
id 选择器 id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式. id 选择器以 "#" 来定义. 下面的两个 id 选择器,第一个可以定义元素的颜色为红色,第二 ...
- Mysql对用户操作加审计功能——高级版
在MYSQL中,每个连接都会先执行init-connect,进行连接的初始化.我们可以在这里获取用户的登录名称和thread的ID值.然后配合binlog,就可以追踪到每个操作语句的操作时间,操作人等 ...
- ios 开发小技巧一
对于UITableViewCell中的textField/textView,你肯定想让它编辑时可以把所在行滚动到键盘上方.如果你的VC是UITableViewController或者子类,那么只要在o ...
- Jquery 之 使用选择器
jQuery选择器描述 jQuery选择器是jQuery框架的基础,jQuery对事件的处理.DOM操作.CSS动态控制.Ajax通信.动画设计都是在选择器基础上进行的.jQuery 选择器采用CSS ...
- HBase体系结构
HBase的服务器体系结构遵从简单的主从服务器架构,它由HRegion服务器(HRegion Service)群和HBase Master服务器(HBase Master Server)构成.Hbas ...
- 54. Search a 2D Matrix && Climbing Stairs (Easy)
Search a 2D Matrix Write an efficient algorithm that searches for a value in an m x n matrix. This m ...
- Runloop基础知识
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
- VBS基本知识
由于一些需要,开始学习VBS了.此篇文章一直将处于编辑添加状态. 1.VBS简介 VBS 即VBScript(Microsoft Visual Basic Script Editon),是微软开发的一 ...
- VBS操作剪切板
'设置剪切板的内容 Dim Form, TextBox Set Form = CreateObject("Forms.Form.1") Set TextBox = Form.Con ...