Categories
All 算法

做題筆記:Remove Duplicates from Sorted Array (Java)

今後 Easy 題若沒碰到非常精彩的就不每題都更了。

題目描述:

給定一個按非遞減順序排序的整數數組 nums,就地刪除重複項,使每個單獨的元素只出現一次。元素的相對順序應保持不變。

由於在某些語言中無法更改數組的長度,因此您必須將結果放在數組 nums 的前半部分。更正式地說,如果刪除重複項後有 k 個元素,則 nums 的前 k 個元素應持有最終結果。除了前 k 個元素之外,留下什麼都不重要。

將最終結果放入 nums 的前 k 個插槽後返回 k值。

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Stack 解法:

自己還是只能想出來蠢方法,應該刷題量還遠遠不夠吧:

class Solution {
    public int removeDuplicates(int[] nums) {
		Stack<Integer> Stack = new Stack<Integer>();
		int k = 0;
		for (int i = 0; i < nums.length; i++) {
			if (Stack.search(nums[i])==-1) {
				Stack.push(nums[i]);
				nums[k] = nums[i];
				k++;
			} 
		}
		return k;
	}
}

7 ms

利用順序的取巧方法:

class Solution {
    public int removeDuplicates(int[] nums) {
        int i = 0;
        for(int n: nums){
            if(i == 0 || n > nums[i - 1]){
                nums[i] = n;
                i++;
            }
        }
        return i;
    }
}

1 ms

Categories
All 算法

做題筆記:Merge Two Sorted Lists (Java)

題目描述:

給定兩個排好序的 linked list list1list2 的 head。

將前兩個 linked list 的節點拼接在一起合併到一個完成排序的 linked list 中。

返回合併之後的鏈結串列的 head。

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []
Output: []

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

解法:

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode result = new ListNode();
        ListNode head = result;
        while (true){
            if (list1==null){
                result.next=list2;
                break;
            }
            if (list2==null){
                result.next=list1;
                break;
            }
            if (list1.val<=list2.val){
                result.next=list1;
                list1=list1.next;
            }
            else {
                result.next=list2;
                list2=list2.next;
            }
            result=result.next;
        }
        return head.next;
    }
}

1 ms

Categories
算法 All

做題筆記:Valid Parentheses (Java)

題目描述:

給定一個僅包含字符 '(', ')', '{', '}', '['']' 的字符串 s,確定輸入字符串是否有效。

有效的情況指:

  1. 前括號必須用相同類型的括號閉合。
  2. 前括號必須以正確的順序閉合。

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

暴力解法:

昨天半夜擼的,還是想不到什麽好點子:

class Solution {
    public boolean isValid(String s) {
        StringBuilder sb = new StringBuilder();
        sb.append(s);
        
        for(int i = 0; i<sb.length()-1; i++ ){
            if ( (sb.charAt(i) == '(' && sb.charAt(i+1) == ')') || 
                 (sb.charAt(i) == '[' && sb.charAt(i+1) == ']') || 
                 (sb.charAt(i) == '{' && sb.charAt(i+1) == '}') 
               ){
                sb = sb.deleteCharAt(i+1);
                sb = sb.deleteCharAt(i);
                i = -1;
            }
        }
        if (sb.toString() == ""){
            return true;
        }
        else{
            return false;
        }
    } 
}

79 ms,慘不忍睹。

Stack 解法:

Hint 中已經提到,應該使用 Stack :

class Solution {
    public boolean isValid(String s) {
	   Stack<Character> stack = new Stack<Character>();
	   for (char c : s.toCharArray()) {
		   if (c == '(')
			   stack.push(')');
		   else if (c == '{')
			   stack.push('}');
		   else if (c == '[')
			   stack.push(']');
		   else if (stack.isEmpty() || stack.pop() != c)
			   return false;
	   }
	   return stack.isEmpty();
    }
}

2 ms

Categories
算法 All

做題筆記:Longest Common Prefix (Java)

還滿難的一道題。

題目描述:

編寫一個函數來查找字符串數組中最長的共有前綴字符串。

如果沒有共有前綴,則返回一個空字符串""

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Horizontal scanning:

自己嘗試的方法:

class Solution {
    public String longestCommonPrefix(String[] strs)
    {
        int size = strs.length;
        if (size == 0)
            return "";

        if (size == 1)
            return strs[0];

        Arrays.sort(strs);
        int end = Math.min(strs[0].length(), strs[size-1].length());
        int i = 0;
        while (i < end && strs[0].charAt(i) == strs[size-1].charAt(i) )
            i++;
        String pre = strs[0].substring(0, i);
        return pre;
    }
}

1 ms

Vertical scanning:

Solution 中提供的方法二:

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";
    for (int i = 0; i < strs[0].length() ; i++){
        char c = strs[0].charAt(i);
        for (int j = 1; j < strs.length; j ++) {
            if (i == strs[j].length() || strs[j].charAt(i) != c)
                return strs[0].substring(0, i);             
        }
    }
    return strs[0];
}

Divide and conquer:

Solution 中提供的方法三:

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";    
        return longestCommonPrefix(strs, 0 , strs.length - 1);
}

private String longestCommonPrefix(String[] strs, int l, int r) {
    if (l == r) {
        return strs[l];
    }
    else {
        int mid = (l + r)/2;
        String lcpLeft =   longestCommonPrefix(strs, l , mid);
        String lcpRight =  longestCommonPrefix(strs, mid + 1,r);
        return commonPrefix(lcpLeft, lcpRight);
   }
}

String commonPrefix(String left,String right) {
    int min = Math.min(left.length(), right.length());       
    for (int i = 0; i < min; i++) {
        if ( left.charAt(i) != right.charAt(i) )
            return left.substring(0, i);
    }
    return left.substring(0, min);
}

Binary search:

Solution 中提供的方法四:

public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0)
        return "";
    int minLen = Integer.MAX_VALUE;
    for (String str : strs)
        minLen = Math.min(minLen, str.length());
    int low = 1;
    int high = minLen;
    while (low <= high) {
        int middle = (low + high) / 2;
        if (isCommonPrefix(strs, middle))
            low = middle + 1;
        else
            high = middle - 1;
    }
    return strs[0].substring(0, (low + high) / 2);
}

private boolean isCommonPrefix(String[] strs, int len){
    String str1 = strs[0].substring(0,len);
    for (int i = 1; i < strs.length; i++)
        if (!strs[i].startsWith(str1))
            return false;
    return true;
}
Categories
All 技術 算法

做題筆記:Roman to Integer (Java)

題目描述:

將羅馬數字轉換為整數,具體規則略。

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

自己的 Switch 暴力解法:

兜了好幾個圈……

class Solution {
    public int romanToInt(String s) {
        int num = 0;
        StringBuilder re = new StringBuilder();
        re.append(s).reverse();
        String[] split = re.toString().split("(?<=\\G..)");
        for (String i:split){
            switch(i){
                case "VI":
                    num = num + 4;
                    break;
                case "XI":
                    num = num + 9;
                    break;
                case "LX":
                    num = num + 40; 
                    break;
                case "CX":
                    num = num + 90; 
                    break;
                case "DC":
                    num = num + 400;
                    break;
                case "MC":
                    num = num + 900; 
                    break;
                default:
                    String[] sub = i.split("");
                    for (String j:sub){
                        switch(j){
                            case "I":
                                num = num + 1;
                                break;
                            case "V":
                                num = num + 5;
                                break;
                            case "X":
                                num = num + 10; 
                                break;
                            case "L":
                                num = num + 50; 
                                break;
                            case "C":
                                num = num + 100;
                                break;
                            case "D":
                                num = num + 500; 
                                break;
                            case "M":
                                num = num + 1000;     
                                break;
                        }
                    }
                }
        }
        return num;    
    }
}

意外發生了,本地 IDE 能跑出正確答案,但是在 Leetcode 上跑不出來,我竟然為這種問題浪費了不少時間,最終也沒解決……

正確精練的 Switch 解法:

class Solution {
	 public int romanToInt(String s) {
	    int nums[] = new int[s.length()];
	    for(int i = 0; i < s.length(); i++){
	        switch (s.charAt(i)) {
	            case 'M':
	                nums[i] = 1000;
	                break;
	            case 'D':
	                nums[i] = 500;
	                break;
	            case 'C':
	                nums[i] = 100;
	                break;
	            case 'L':
	                nums[i] = 50;
	                break;
	            case 'X' :
	                nums[i] = 10;
	                break;
	            case 'V':
	                nums[i] = 5;
	                break;
	            case 'I':
	                nums[i] = 1;
	                break;
	        }
	    } 
	    
	    int sum = 0;
	    for(int i=0; i<nums.length-1; i++){
	        if(nums[i] < nums[i+1])
	            sum -= nums[i];
	        else
	            sum += nums[i];
	    }
         
	    return sum + nums[nums.length-1];
	}
}

6 ms

運用 Hashmap:

class solution {
    public int romanToInt(String s) {
        Map map = new HashMap<>();
        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 result = map.get(s.charAt(s.length()-1));
        for(int i=s.length()-2; i>=0; i--){
            if(map.get(s.charAt(i)) < map.get(s.charAt(i+1))){
                result -= map.get(s.charAt(i));
            }
            else{
                result += map.get(s.charAt(i));
            }
        }
        return result;
    }
}

Categories
All 算法

做題筆記:Palindrome Number (Java)

題目描述:

給定一個整數 x,如果 x 是回文數,則返回 true

回文數指一個整數向後讀和向前讀内容相同。

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

算術解法:

利用 Java 整數倒序計算:

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }
        
        int ori = x;
        int p = 0;
        while (ori != 0) {
            p = p * 10 + ori % 10;
            ori /= 10;
        }
        
        return x == p;
    }
}

9 ms,超過 87.67% 的答案。

轉換為 String 的解法:

進階要求 Follow Up 竟然問了一句 Could you solve it without converting the integer to a string? 原來我想到的已經是進階方法了,常規解法是轉換為 String:

class Solution {
     public boolean isPalindrome(int x) {
         char[] nums = String.valueOf(x).toCharArray();
         int start = 0;
         int end = nums.length-1;
         while(start < end) {
             if(nums[start] != nums[end]) return false;
             start++; end--;
         }
        return true;
    }
}

19 ms,超過 19.48% 的答案。

Categories
All 算法

做題筆記:Two Sum (Java)

驚恐自己要找不到工作了,開始做題,記錄一下做題筆記。第一道,是刷題界的 Hello World —— Two Sum。

題目描述:

給定一個整數數組 nums 和一個整數 target,返回兩個數字的索引,使它們相加為 target

假設每個輸入都只有一個解決方案,並且不會使用相同的元素兩次。

可以按任何順序返回答案。

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Foreach 暴力解法:

第一次刷題,算法小白,只想得到這種方式:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int [] empty = new int[2];
        int len = nums.length;
        for(int i = 0; i < len; i++){
            for(int j = 0; j < len; j++){
                    if (nums[i]+nums[j] == target&& i != j){
                        empty[0] = i;
                        empty[1] = j;
                        return empty;
                    }
            }
        }
        return null;
    }
}

果不其然,106 ms,超過了10%的答案,好歹是通過了對吧……

以前上課做作業時,都是秉持著能跑就行的態度,習慣很差,現在我開始認真考慮優化的問題了,也算是一大進步。

Hashmap 解法:

看了 discussion 之後,追求高效率,這道題是應該使用 Hashmap 的:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
        map.put(numbers[i], i);
    }
    return result;
}
}

3 ms,超過85%的結果。