Menu Sidebar
Menu

Enumeration

[LintCode] Majority Number

public int majorityNumber(ArrayList<Integer> nums) { // write your code int index = -1; int count = 0; for(int i = 0 ; i < nums.size(); i++) { if(count == 0) { index = i; count ++; } else { if(nums.get(i) == nums.get(index)) count++; else count–; } } return nums.get(index); }

[LintCode] Longest Words

ArrayList<String> longestWords(String[] dictionary) { // write your code here ArrayList<String> res = new ArrayList<String>(); if(dictionary == null || dictionary.length == 0) return res; int len = dictionary[0].length(); for(int i = 0; i < dictionary.length; i++) { if(dictionary[i].length() == len) res.add(dictionary[i]); else if(dictionary[i].length() > len){ len = dictionary[i].length(); res.clear(); res.add(dictionary[i]); } } return res; }

[LintCode] Fizz Buzz

public ArrayList<String> fizzBuzz(int n) { ArrayList<String> results = new ArrayList<String>(); for (int i = 1; i <= n; i++) { if (i % 15 == 0) { results.add(“fizz buzz”); } else if (i % 5 == 0) { results.add(“buzz”); } else if (i % 3 == 0) { results.add(“fizz”); } else { results.add(String.valueOf(i)); } } […]

[LintCode] Fibonacci

public int fibonacci(int n) { // write your code here int first = 0; if(n == 1) return first; int second = 1; if(n == 2) return second; int third = 0; for(int i = 3; i <=n; i++) { third = first+ second; first = second; second = third; } return third; }

[LintCode] Longest Common Prefix

public String longestCommonPrefix(String[] strs) { // write your code here if(strs == null || strs.length == 0) return “”; String prefix = strs[0]; for(int i = 1; i < strs.length; i++) { int j = 0; while(j < prefix.length() && j < strs[i].length() && prefix.charAt(j)==strs[i].charAt(j)) j++; prefix = prefix.substring(0,j); } return prefix; }

书脊

这青苔碧瓦堆, 俺曾睡风流觉, 将五十年兴亡看饱.

December 2024
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031