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(四)的更多相关文章

  1. leetcode 四数之和

    这里我们可以考虑将 n 数之和降低为一个数加上 n-1 数之和的问题.依次降低 ,最低是二数之和的问题 ,二数之和问题容易解决.主要在于从 n 到 n-1 的过程需要理解 :下列代码中前几个 if 是 ...

  2. day07整理(内置方法\循环判断)

    目录 一.上节课回顾 (一)if判断 1.单分支结构 2.双分支结构 3.多分支结构 (二)for循环 1.for + break 2.for + continue 3.for循环嵌套 (三)robu ...

  3. [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 ...

  4. [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 ...

  5. Leetcode:LRUCache四个版本实现

    题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...

  6. 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 ...

  7. LeetCode第四天

    leetcode 第四天 2018年1月4日 15.(628)Maximum Product of Three Numbers JAVA class Solution { public int max ...

  8. [LeetCode] 4 Keys Keyboard 四键的键盘

    Imagine you have a special keyboard with the following keys: Key 1: (A): Print one 'A' on screen. Ke ...

  9. LeetCode算法题-Minimum Distance Between BST Nodes(Java实现-四种解法)

    这是悦乐书的第314次更新,第335篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第183题(顺位题号是783).给定具有根节点值的二叉搜索树(BST),返回树中任何两个 ...

随机推荐

  1. jQuery使用load方法加载其他文档内容

    A文档载入B文档的内容,并且通过JQ操作被引入到A文档中的元素 A文档 (index.html): <!DOCTYPE html> <html lang="en" ...

  2. 使用 Jmeter 做 Web 接口测试

    接口测试概述 定义 API testing is a type of software testing that involves testing application programming in ...

  3. vmware workstation LINUX磁盘扩容

    1.edit virtual machine settings -> 选中硬盘->右侧utilities->expand(虚拟机不能存在镜像),输入要扩容到的大小 2.扩容之后进入系 ...

  4. Android:去掉默认的标题bar

    要使用自己定义的bar,只需要在layout文件中添加:<include layout="@layout/actionbar" />;当然你需要新建一个actionba ...

  5. Flex加载google地图、百度地图以及天地图作底图

    一  Flex加载Google地图作底图 (1)帮助类GoogleLayer.as /* * 根据输入的地图类型加载Google地图(by chenyuming) */ package Layers ...

  6. oracle client与ODAC的字符集

    1.pl/sql developer 9里检查客户端字符集与服务端是否一致 首选项,选项,检查客户机与服务器字符集是否匹配 2.Windows环境变量的修改即时生效 3.ODAC12安装后字符集的变化 ...

  7. CPU阿甘

    本系列文章全部摘选自"码农翻身"公众号,仅供个人学习和分享之用.文章会给出原文的链接地址,希望不会涉及到版权问题. 个人感言:真正的知识是深入浅出的,码农翻身" 公共号将 ...

  8. Http的请求对象

    Servlet 客户端 HTTP 请求 当浏览器请求网页时,它会向 Web 服务器发送特定信息,这些信息不能被直接读取,因为这些信息是作为 HTTP 请求的头的一部分进行传输的.您可以查看 HTTP ...

  9. SQLSERVER | 查询数据库中所有的表的名字 | 查询数据库中的所有数据库名

    SQLSERVER 1.查询某个数据库中所有的表名:  SELECT Name FROM SysObjects Where XType='U' ORDER BY Name 2.查询数据库中的所有数据库 ...

  10. 属性传值,协议传值,block传值,单例传值四种界面传值方式

    一.属性传值 对于属性传值而言,相对于其它的三种 方法来说,是最基础,最简单的一种 方法,但,属性传值 有很大的局限性,因为是适用于第一个界面向第二个界面传 值,第二个向第三个界面传值等等.N界面向N ...