1. 程式人生 > >LeetCode 答案(Easy)(1-100)

LeetCode 答案(Easy)(1-100)

1-Two Sum(兩數求和)

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, and you may not use the same element twice.
你需要確保每個輸入的陣列都有一個確定的解,並且每個元素只能使用一次。

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
  • 答案
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0, length = nums.length; i < length; i++) {

            for (int j = i + 1; j < length; j++) {

                if
(nums[i] + nums[j] == target) { int[] newNum = { i, j }; //System.out.println("["+i+","+j+"]"); return newNum; } } } return null; } }

7-Reverse Integer(逆置整數)

Reverse digits of an integer.
逆置一個整數
Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

  • 答案
public class Solution {
    public int reverse(int x) {
        String start = x + "";
        char[] arr = start.toCharArray();
        StringBuffer sb = new StringBuffer();
        if (x >= 0) {
            for (int length = arr.length, i = length - 1; i >= 0; i--) {
                sb.append(arr[i]);
            }
            try {
                return Integer.parseInt(sb.toString());
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                return 0;
            }
        } else {
            for (int length = arr.length, i = length - 1; i > 0; i--) {
                sb.append(arr[i]);
            }
            try {
                return Integer.parseInt("-" + sb.toString());
            } catch (NumberFormatException e) {
                return 0;
            }
        }


    }
}

9-Palindrome Number(迴文數字)

Determine whether an integer is a palindrome. Do this without extra space.
確認一個整數是否是迴文數。不要使用額外的儲存空間
click to show spoilers.

Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

  • 答案
public class Solution {
    public boolean isPalindrome(int x) {
        String xString = x + "";
        int count = 0, length = xString.length(), middle = length / 2;
        for (int i = 0; i < middle; i++) {
            if (xString.charAt(i) == xString.charAt(length - 1 - i)) {
                count++;
            }
        }
        if (count == middle) {
            return true;
        } else {
            return false;
        }

    }
}

13-Roman to Integer (羅馬數轉阿拉伯數)

Given a roman numeral, convert it to an integer.
輸入一個羅馬數,轉換成阿拉伯數

Input is guaranteed to be within the range from 1 to 3999.
輸入的範圍是1-3999

  • 答案
public class Solution {
    public int romanToInt(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);

        int sum = map.get(s.charAt(0)), length = s.length();
        for (int i = 1; i < length; i++) {

            if (map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) {
                sum = sum + map.get(s.charAt(i)) - 2 * map.get(s.charAt(i - 1));

            } else {
                sum += map.get(s.charAt(i));
            }

        }

        return sum;




    }
}

20-Valid Parentheses (有效的括號字串)

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
給定一個字串,只包括’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 以及 ‘]’這些字元,確認它是否有效。

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
括號必須要正確的關閉,”()” 和”()[]{}”是有效的,但是 “(]” 和”([)]” 無效
- 答案

public class Solution {
    public boolean isValid(String s) {
        boolean result= false;  
        //while迴圈的次數
        int countwhile =0;
        //匹配到的對的數量
        int num=0;
        //輸入的字串的長度
        int paramLenth =s.length();
        while(countwhile<paramLenth){
            char[] chs = s.toCharArray();
            w: for(int i=1,length=chs.length;i<length;i++){
                String str=s.charAt(i-1)+""+s.charAt(i);
                if(str.equals("{}")||str.equals("()")||str.equals("[]")){
                    num ++;
                    s=s.substring(0, i-1)+s.substring(i+1, s.length());
                    break w;

                }
            }
            countwhile++;

        }
        if(num==paramLenth/2&&paramLenth%2==0){
            result= true;
        }
        return result;
    }
}

28-Implement strStr() [ 實現strStr() 即indexOf()]

Implement strStr().
實現strStr() 即indexOf()

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
返回needle第一次出現在haystack時的索引,如果不存在就返回 -1

  • 答案
public class Solution {
    public int strStr(String haystack, String needle) {

        int needleLength=needle.length();
        int haystackLength = haystack.length();
        int result=-1;
        if("".equals(needle)){
            return 0;
        }
        for (int i =needleLength-1 ; i < haystackLength; i++) {
            String moveableString=haystack.substring(i+1-needleLength, i+1);
            if(moveableString.equals(needle)){
                result=i+1-needleLength;
                break;
            }
        }
        return result;

    }
}

35-Search Insert Position (查詢插入位置)

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
給定一個已經排好序的陣列(升序) 以及一個目標值,返回目標值在陣列中的位置,如果不存在,那麼就返回目標值應該放在的未知的索引

You may assume no duplicates in the array.
陣列中沒有重複元素

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

  • 答案
public class Solution {
    public int searchInsert(int[] nums, int target) {


        int length = nums.length;
        int start = 0;
        int end = length - 1;

        while (start <= end) {
            // System.out.println(start+"----"+end);
            int middle = (start + end) / 2;
            if (nums[middle] > target) {
                end = middle - 1;

            } else if (nums[middle] < target) {
                start = middle + 1;
            } else {
                return middle;
            }
        }
        return start;



    }
}

53-Maximum Subarray (最大的子陣列)

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
擷取陣列,找出和最大的子陣列。元素要相鄰且至少有一個元素。

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
例如:給定的陣列 [-2,1,-3,4,-1,2,1,-5,4],
相鄰的子陣列 [4,-1,2,1] 有一個最大的和 6

click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

  • 答案
//典型的動態規劃問題:
//思路:
//首先,很顯然在連續累加的過程中,加了nums[i]如果sum是小於0的,那麼說明前一次計算出的sums其副作用,  需要重新尋找起始開始累加
//即重新以當前nums[i]為起始值開始累加
public class Solution {
    public int maxSubArray(int[] nums) {

    int maxSum = nums[0];//記錄累加過程中的最大值
    int subSum = nums[0];
    for(int i = 1; i < nums.length; i++)
    {
        subSum = subSum <= 0? nums[i] : subSum+nums[i];
        if(subSum > maxSum) 
            maxSum = subSum;
    }
    return maxSum;


    }
}

58-Length of Last Word(最後一個單詞的長度)

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
給定一個由大小寫字母以及空格構成的句子,返回句子中最後一個單詞的長度

If the last word does not exist, return 0.
如果不存在最後一個單詞 ,返回0

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = “Hello World”,
return 5.

  • 答案
class Solution {
    public int lengthOfLastWord(String s) {
        //按" "將字串分成單詞的陣列
        String[] words=s.trim().split(" ");
        //返回陣列中最後一個單詞的長度
        return words[words.length-1].length();

    }
}

69-Sqrt(x) 求平方根

Implement int sqrt(int x).
實現 int sqrt(int x)

Compute and return the square root of x.
計算並返回x的平方根

  • 答案
public class Solution {
    public int mySqrt(int x) {




        double start = 0, end = x;
        double middle = 1;
        double result = 1;

        while (Math.abs(x - result) > 0.000001) {
            middle = (start + end) / 2;
            result = middle * middle;

            if (result <= x) {
                start = middle;

            } else {
                end = middle;

            }

        }
        //System.out.println(middle);
        return (int) middle;





    }
}