首页 > 代码库 > Leetcode刷题记录

Leetcode刷题记录

1. Two Sum  --No Bug Free

技术分享
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
View Code

1st: O(n2)算法,可以用空间换时间,用hashmap存储,降到O(n)。

技术分享
 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int [] res = new int[2];
 4         for (int i = 0; i < nums.length - 1; i++) {
 5             for (int j = i + 1; j < nums.length; j++) {
 6                 if (nums[i] + nums[j] == target) {
 7                     res[0] = i;
 8                     res[1] = j;
 9                     return res;
10                 }
11             }
12         }
13         return res;
14     }
15 }
View Code
技术分享
 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         Map<Integer, Integer> hash = new HashMap<Integer,Integer>();
 4         int [] res = new int[2];
 5         for (int i = 0; i < nums.length; i++) {
 6             if (hash.containsKey(target - nums[i])) {
 7                 res[0] = hash.get(target - nums[i]);
 8                 res[1] = i;
 9                 return res;
10             }
11             hash.put(nums[i], i);
12         }
13         return res;
14     }
15 }
View Code

6. ZigZag Conversion -- No Bug Free

技术分享
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
View Code

1 st : 索引范围没取好

按每行索引存储

技术分享
 1 public class Solution {
 2     public String convert(String s, int numRows) {
 3         if (s.length() < 3 || numRows == 1){
 4             return s;
 5         }
 6         int cycle = 2 * numRows - 2;
 7         StringBuffer res = new StringBuffer(s.length());
 8         for (int i = 0; i < s.length(); i += cycle) {
 9             res.append(s.charAt(i));
10         }
11         for (int i = 1; i < numRows - 1; i++) {
12             for (int j = i; j < s.length(); j+= cycle) {
13                 res.append(s.charAt(j));
14                 if (j + cycle - 2 * i < s.length()) {
15                     res.append(s.charAt(j + cycle - 2 * i));
16                 }
17             }
18         }
19         for (int i = numRows - 1; i < s.length(); i += cycle) {
20             res.append(s.charAt(i));
21         }
22         return res.toString();
23     }
24 }
View Code

先转成char数组更快

技术分享
 1 public class Solution {
 2     public String convert(String s, int numRows) {
 3         if (s.length() < 3 || numRows == 1){
 4             return s;
 5         }
 6         char [] c = s.toCharArray();
 7         int cycle = 2 * numRows - 2;
 8         StringBuffer res = new StringBuffer(s.length());
 9         for (int i = 0; i < s.length(); i += cycle) {
10             res.append(c[i]);
11         }
12         for (int i = 1; i < numRows - 1; i++) {
13             for (int j = i; j < s.length(); j+= cycle) {
14                 res.append(c[j]);
15                 if (j + cycle - 2 * i < s.length()) {
16                     res.append(c[j + cycle - 2 * i]);
17                 }
18             }
19         }
20         for (int i = numRows - 1; i < s.length(); i += cycle) {
21             res.append(c[i]);
22         }
23         return res.toString();
24     }
25 }
View Code

或按每列存储

技术分享
 1 public class Solution {
 2     public String convert(String s, int nRows) {
 3         char[] c = s.toCharArray();
 4         int len = c.length;
 5         StringBuffer[] sb = new StringBuffer[nRows];
 6         for (int i = 0; i < sb.length; i++){
 7             sb[i] = new StringBuffer();
 8         }
 9         int i = 0;
10         while (i < len) {
11             for (int idx = 0; idx < nRows && i < len; idx++){ // vertically down
12                 sb[idx].append(c[i++]);
13             }
14             for (int idx = nRows - 2; idx >= 1 && i < len; idx--){ // obliquely up
15                 sb[idx].append(c[i++]);
16             }
17         }
18         for (int idx = 1; idx < sb.length; idx++) {
19             sb[0].append(sb[idx]);
20         }
21         return sb[0].toString();
22     }
23 }
View Code

7. Reverse Integer

技术分享
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321
View Code

注意溢出

技术分享
 1 public class Solution {
 2     public int reverse(int x) {
 3         long sum = 0;
 4         while(x != 0){
 5             sum = sum * 10 + x % 10;
 6             x = x/10;
 7         }
 8         if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE)
 9             return 0;
10         return (int)sum;
11     }
12 }
View Code

或者判断乘10后,再除10是否相等。

技术分享
 1 public class Solution {
 2     /**
 3      * @param n the integer to be reversed
 4      * @return the reversed integer
 5      */
 6     public int reverseInteger(int n) {
 7         int reversed_n = 0;
 8         
 9         while (n != 0) {
10             int temp = reversed_n * 10 + n % 10;
11             n = n / 10;
12             if (temp / 10 != reversed_n) {
13                 reversed_n = 0;
14                 break;
15             }
16             reversed_n = temp;
17         }
18         return reversed_n;
19     }
20 }
View Code

8. String to Integer (atoi) -- No Bug Free

技术分享
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
View Code

注意大量的corner case, 1 str == null str.length() == 0, 溢出 空格 正负号等

技术分享
 1 public class Solution {
 2     public int myAtoi(String str) {
 3         if (str == null || str.length() == 0) {
 4             return 0;
 5         }
 6         long sum = 0;
 7         int i = 0;
 8         int positive = 1;
 9         while (str.charAt(i) == ‘ ‘){
10             i++;
11         }
12         if (str.charAt(i) == ‘+‘){
13             i++;
14         } else if (str.charAt(i) == ‘-‘) {
15             i++;
16             positive = -1;
17         }
18         while (i < str.length() && str.charAt(i) <= ‘9‘ && str.charAt(i) >= ‘0‘) {
19             sum = sum * 10 + str.charAt(i) - ‘0‘;
20             i++;
21             if (sum > Integer.MAX_VALUE) {
22                 return positive == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
23             }
24         }
25         return positive * (int) sum;
26     }
27 }
View Code

 9. Palindrome Number -- No BUg Free

技术分享
Determine whether an integer is a palindrome. Do this without extra space.(回文数)
View Code

注意corner case 溢出,结尾为0,其余的回文,负数等

技术分享
 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         if (x < 0 || ( x !=0 && x % 10 == 0)) {
 4             return false;
 5         }
 6         int rev = 0;
 7         while (rev < x) {
 8             rev = rev * 10 + x % 10;
 9             x = x / 10;
10         }
11         return (x == rev || x == rev / 10);
12     }
13 }
View Code

 

Leetcode刷题记录