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),返回树中任何两个 ...
随机推荐
- Node调试之道-----JSHint
Node调试之道-----JSHint Node的优势我就不再乱吹捧了,它让javascript统一web的前后台成为了可能.但是对于新手来说,server端的JS代码可能不像client端的代码那么 ...
- lumen 错误&日志
1.简介 开始一个新的Lumen项目的时候,错误和异常处理已经默认为你配置好了.此外,Lumen还集成了提供各种功能强大日志处理器的Monolog日志库. 2.配置 2.1 错误详情 配置文件.env ...
- Null modem接线
1.6 <-> 4 2 <-> 3 3 <-> 2 4 <-> 1.6 5 <-> 5 7 <-> 8 8 <-> ...
- [内核]Linux workqueue
转自:http://blog.chinaunix.net/uid-24148050-id-296982.html 一.workqueue简介workqueue与tasklet类似,都是允许内核代码请求 ...
- Spring-RMI固定端口
Spring-RMI固定端口 最近接到一个需求项目所应用的RMI端口(数据传输端口)为随机指定的,项目要求对其端口固定,费劲周折找了很多资料,最后解决了问题. 其实解决问题的方法及其简单,只需要在 ...
- python的json模块
Python JSON 本章节我们将为大家介绍如何使用 Python 语言来编码和解码 JSON 对象. 环境配置 在使用 Python 编码或解码 JSON 数据前,我们需要先安装 JSON 模块. ...
- 关于MOD
同余式:正整数a,b对p取模,它们的余数相同,(a % p)=(b % p) 记做 或者a ≡ b (mod p). 运算规则 模运算与基本四则运算有些相似,但是除法例外.其规则如下: ...
- 44. Decode Ways && Gray Code
Decode Ways A message containing letters from A-Z is being encoded to numbers using the following ma ...
- Windows、VS 与 .net
原文地址:https://msdn.microsoft.com/en-us/library/bb822049(v=vs.110).aspx .NET Framework version CLR ver ...
- android开发--布局三(微信布局)
微信主界面 我们布局应该从局来看,如上图,我们可以分为三个大的LinearLayout,再从LinearLayout嵌套其它布局,从而做出界面 文件 主界面代码: <LinearLayout x ...