LeetCode算法代碼筆記(31-35)

給自己的目標:[LeetCode](https://leetcode.com/ "Online Judge Platform") 上每日一題

在做題的過程中記錄下解題的思路或者重要的代碼碎片以便后來翻閱。
項目源碼:github上的Leetcode

31. Next Permutation

題目:給出一個序列,尋找比當前排列順序大的下一個排列。規則如下:

1,2,3 ->next
1,3,2 ->next
2,1,3 ->next
2,3,1 ->next
3,1,2 ->next
3,2,1 ->next
1,2,3 ->loop

因為是找遞增的下一個排列,所以從后往前找到第一個升序對的位置,如1,2,4,3,1, 從后向前找就是2,4,3,1,因為2比前一個數4小,所以就鎖定2這個數。
之后就是在4,3,1中找到比2大的最小的那個數3,將3與2對換得到降序排列4,2,1.然后就是將4,2,1反序得到1,2,4.最終結果就是1,3,1,2,4

public class Solution {
    public void nextPermutation(int[] nums) {
        if (nums.length == 0 || nums.length == 1) return;
        int len = nums.length;
        int index = len - 1;
        int value = nums[index];
        for (index = index - 1; index >= 0; index--) {
            if (nums[index] < value) {
                value = nums[index];
                break;
            }
            value = nums[index];
        }
        if (index < 0) {
            reversal(nums, 0, len - 1);
        } else {
            for (int j = len - 1; j > index; j--) {
                if (nums[j] > value) {
                    nums[index] = nums[j];
                    nums[j] = value;
                    reversal(nums, index + 1, len - 1);
                    break;
                }
            }
        }
    }

    public void reversal(int[] nums, int start, int end) {
        int len = end + 1 - start;
        for (int i = 0; i < len / 2; i++) {
            int k = nums[start + i];
            nums[start + i] = nums[end - i];
            nums[end - i] = k;
        }
    }
}

32. Longest Valid Parentheses

題目:輸入一串只包含"(",")"的字符串,求合法子串的最大值。

")()())", where the longest valid parentheses substring is "()()", which has length = 4.

一道很容易TLE的題目,最優解法是使用 stack 記錄字符串中"("出現時的index,當出現")"進行匹配時相減得到長度。

public class Solution {
    public int longestValidParentheses(String s) {
        if (s.isEmpty()) return 0;
        Stack<Integer> ms = new Stack<>();
        int maxlen = 0;
        int last = -1;  // Position of the last unmatched ')'
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') ms.push(i); //
            else if (ms.empty()) last = i; // == ')' and the stack is empty, it means this is a non-matching ')'
            else {
                ms.pop();           // pops the matching '('.
                if (ms.empty()) // If there is nothing left in the stack, it means this ')' matches a '(' after the last unmatched ')'
                    maxlen = Math.max(maxlen, i - last);
                else    // otherwise,
                    maxlen = Math.max(maxlen, i - ms.peek());
            }
        }
        return maxlen;
    }
}

33.Search in Rotated Sorted Array

題目:給出一組有序的數組,如 0 1 2 4 5 6 7,將其分成兩段并互換,比如會成為4 5 6 7 0 1 2。給出一個 target 值,求在數組中的位置,若不存在輸出-1

一種最簡單的方法是直接遍歷過,時間復雜度為O(n),另一種是先使用 binary search 找出旋轉點(最小值)所在的位置,之后在用二分遍歷一次獲得 target 所在的位置。

/**
* 簡單遍歷
*/
public class Solution {
    public int search(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return i;
            }
        }
        return -1;
    }
}

34. Search for a Range

題目:給出一個有序的數組和一個目標值,求該目標值在數組的范圍(由于目標值在數組中存在好幾個)。要求時間復雜度為O(logn)

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

一個很簡單的二分查找題,要注意的是即使找到一個目標值也要繼續向左右查找下去以便確定目標值在數組中的范圍。

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int start = -1, end = -1;
        int st = 0, len = nums.length - 1;
        while (st <= len) {
            int mid = (len + st + 1) / 2;
            if (nums[mid] == target) {
                start = binarySearch(nums, st, mid - 1, target, true);
                end = binarySearch(nums, mid + 1, len, target, false);
                if (start == -1) start = mid;
                if (end == -1) end = mid;
                break;
            } else if (nums[mid] > target) {
                len = mid - 1;
            } else if (nums[mid] < target) {
                st = mid + 1;
            }
        }
        return new int[]{start, end};
    }

    public int binarySearch(int[] nums, int start, int end, int target, boolean left) {
        if (start > end) {
            return -1;
        }
        int mid = (start + end + 1) / 2;
        int index = -1;
        if (nums[mid] == target) {
            if (left) {
                index = binarySearch(nums, start, mid - 1, target, left);
            } else {
                index = binarySearch(nums, mid + 1, end, target, left);
            }
            if (index == -1) {
                return mid;
            }
            return index;
        } else if (nums[mid] > target) {
            return binarySearch(nums, start, mid - 1, target, left);
        } else if (nums[mid] < target) {
            return binarySearch(nums, mid + 1, end, target, left);
        } else {
            return index;
        }
    }
}

35. Search Insert Position

題目:給出一組有序數組和一個目標數字,求目標數字在數組中的位置,沒找到時則求插入數組的位置。

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 len = nums.length;
        int start = 0;
        int end = len - 1;
        int index = start;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (target > nums[mid]) {
                start = mid + 1;
                index = start;
            } else if (target < nums[mid]) {
                end = mid - 1;
                index = mid;
            } else {
                return mid;
            }
        }
        return index;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,763評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,238評論 3 428
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,823評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,604評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,339評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,713評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,712評論 3 445
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,893評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,448評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,201評論 3 357
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,397評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,944評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,631評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,033評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,321評論 1 293
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,128評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,347評論 2 377

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,764評論 0 33
  • LeetCode 刷題隨手記 - 第一部分 前 256 題(非會員),僅算法題,的吐槽 https://leetc...
    蕾娜漢默閱讀 17,888評論 2 36
  • leetcode刷題記錄本文記錄一下leetcode刷題記錄,記錄一下自己的解法和心得。 LeetCode Two...
    EarthChen閱讀 3,496評論 0 6
  • 第5章 引用類型(返回首頁) 本章內容 使用對象 創建并操作數組 理解基本的JavaScript類型 使用基本類型...
    大學一百閱讀 3,263評論 0 4
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,818評論 18 139