隨心情刷Leetcode - 1

q165 比較版本號(hào)

/**
 * Compare two version numbers version1 and version2.
 * If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
 *
 * You may assume that the version strings are non-empty and contain only digits and the . character.
 *
 * The . character does not represent a decimal point and is used to separate number sequences.
 *
 * For instance, 2.5 is not "two and a half" or "half way to version three",
 * it is the fifth second-level revision of the second first-level revision.
 *
 * You may assume the default revision number for each level of a version number to be 0.
 * For example, version number 3.4 has a revision number of 3 and 4
 * for its first and second level revision number.
 * Its third and fourth level revision number are both 0.
 */
public class CompareVersionNum {

    public static void main(String[] args) {
        String test = "0001";
        //System.out.println(Integer.valueOf(test));
        String v1 = "0.1";
        String v2 = "1.1";
        System.out.println(compareVersion(v1, v2));
    }


    /**
     * 自己思路:
     * 兩個(gè)字符串都使用'.'分開(kāi)形成兩個(gè)String字符串?dāng)?shù)組
     * 然后一組一組數(shù)字進(jìn)行比較,如果其中一個(gè)長(zhǎng)度不夠長(zhǎng)的話就用0進(jìn)行比較
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        int len = Math.max(v1.length, v2.length);
        System.out.println(len);
        for (int i=0; i<len;i++){
            int v1Curr = v1.length>i ? Integer.valueOf(v1[i]):0;
            int v2Curr = v2.length>i ? Integer.valueOf(v2[i]):0;
            System.out.println("v1Curr: "+ v1Curr +" v2Curr: "+v2Curr);
            if (v1Curr<v2Curr){
                return -1;
            }else if (v1Curr>v2Curr){
                return 1;
            }

        }

        return 0;

    }
}

q315計(jì)算右側(cè)比當(dāng)前元素小的元素個(gè)數(shù)

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * You are given an integer array nums and you have to return a new counts array.
 * The counts array has the property where counts[i] is the number of smaller elements
 * to the right of nums[i].
 *
 * Example 1:
 * Input: nums = [5,2,6,1]
 * Output: [2,1,1,0]
 * Explanation:
 * To the right of 5 there are 2 smaller elements (2 and 1).
 * To the right of 2 there is only 1 smaller element (1).
 * To the right of 6 there is 1 smaller element (1).
 * To the right of 1 there is 0 smaller element.
 */
public class CountOfSmallerNumAfterSelf {

    /**
     * 最簡(jiǎn)單的做法: 暴力求解 時(shí)間復(fù)雜度 O(n^2)
     * @param nums
     * @return
     */
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for (int i=0;i<nums.length-1;i++){
            int count = 0;
            int label = nums[i];
            for (int j=i+1;j<nums.length;j++){
                if (nums[j]<label){
                    count++;
                }
            }
            res.add(count);
        }
        res.add(0);
        return res;
    }

    /**
     * 使用binarySearch方式
     * 從后往前遍歷 找到在有序的list之中新元素的位置 從而推導(dǎo)出來(lái)有多少個(gè)元素比它小
     * @param nums
     * @return
     */
    public List<Integer> countSmallerTwo(int[] nums){
        List<Integer> res = new ArrayList<>();
        List<Integer> sortedList = new ArrayList<>();

        if (nums == null || nums.length == 0){
            return res;
        }

        res.add(0);
        sortedList.add(nums[nums.length-1]);

        for (int i=nums.length-2; i>=0; i--){
            int index = Collections.binarySearch(sortedList, nums[i]);

            if (index >= 0){
                while (index>0 && sortedList.get(index-1) == nums[i]){
                    index--;
                }
            }else {
                index = -1-index;
            }

            res.add(0,index);
            sortedList.add(index, nums[i]);
        }

        return res;


    }
}

q341 扁平化嵌套列表迭代器

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

/**
 * Given a nested list of integers, implement an iterator to flatten it.
 *
 * Each element is either an integer, or a list -- whose elements may also be integers or other lists.
 */
public class NestedIterator implements Iterator<Integer> {

    Stack<Integer> res;

    public NestedIterator(List<NestedInteger> nestedList){
        Stack<NestedInteger> stack = new Stack<>();
        add(nestedList,stack);
        res = new Stack<>();
        while (!stack.isEmpty()){
            res.add(stack.pop().getInteger());
        }
    }

    public void add(List<NestedInteger> nestedList, Stack<NestedInteger> stack){
        for (NestedInteger i:nestedList){
            if (i.isInteger()){
                stack.add(i);
            }else {
                add(i.getList(),stack);
            }
        }
    }


    @Override
    public boolean hasNext() {
        return !res.isEmpty();
    }

    @Override
    public Integer next() {
        if (hasNext()){
            return res.pop();
        }
        return null;
    }

    public class NestedInteger {

        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger(){
            return false;
        }

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger(){
            return 0;
        }

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return null if this NestedInteger holds a single integer
        public List<NestedInteger> getList(){
            return new ArrayList<>();
        }
    }
}

q394 字符串解碼

import java.util.Stack;

/**
 * Given an encoded string, return its decoded string.
 *
 * The encoding rule is: k[encoded_string], 
 * where the encoded_string inside the square brackets is being repeated exactly k times. 
 * Note that k is guaranteed to be a positive integer.
 *
 * You may assume that the input string is always valid; 
 * No extra white spaces, square brackets are well-formed, etc.
 *
 * Furthermore, you may assume that the original data does not 
 * contain any digits and that digits are only for those repeat numbers, 
 * k. For example, there won't be input like 3a or 2[4].
 */
public class DecodeString {

    public static void main(String[] args) {
        String test = "3[a2[c]]";
        String test2 = "3[ab2[cd]]";
        String test3 = "100[leetcode]";
        System.out.println(decodeString(test3));
    }

    /**
     * 使用兩個(gè)棧,一個(gè)存儲(chǔ)頻率凤跑,一個(gè)存儲(chǔ)括號(hào)和字符声功,每個(gè)左括號(hào)對(duì)應(yīng)一個(gè)頻率
     * @param s
     * @return
     */
    public static String decodeString(String s) {
        Stack<Integer> frequency = new Stack<>();
        Stack<String> alphabet = new Stack<>();


        //temp存儲(chǔ)的在遇到上一個(gè)括號(hào)之內(nèi)遍歷需要形成的String
        StringBuilder temp = new StringBuilder();
        StringBuilder currentStr = new StringBuilder();

        for (int i=0;i<s.length();i++){
            if (Character.isDigit(s.charAt(i))){
                int currNum = 0;
                while (Character.isDigit(s.charAt(i))){
                    currNum = currNum*10 + s.charAt(i)-'0';
                    i++;
                }
                i--;
                frequency.add(currNum);
            } else if (s.charAt(i)==']'){
                while (!alphabet.peek().equals("[")){
                    temp.append(alphabet.pop());
                }

                alphabet.pop();
                int currFrenquency = frequency.pop();

                for (int j=0;j<currFrenquency;j++){
                    currentStr.append(temp.toString());
                }

                alphabet.push(currentStr.toString());
                currentStr.setLength(0);
                temp.setLength(0);
            }else {
                alphabet.add(String.valueOf(s.charAt(i)));
            }
        }

        StringBuilder res = new StringBuilder();
        while (!alphabet.isEmpty()){
            res.append(alphabet.pop());
        }

        return res.reverse().toString();
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末醒串,一起剝皮案震驚了整個(gè)濱河市执桌,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌芜赌,老刑警劉巖仰挣,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異缠沈,居然都是意外死亡膘壶,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門洲愤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)颓芭,“玉大人,你說(shuō)我怎么就攤上這事柬赐⊥鑫剩” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵肛宋,是天一觀的道長(zhǎng)州藕。 經(jīng)常有香客問(wèn)我,道長(zhǎng)悼吱,這世上最難降的妖魔是什么慎框? 我笑而不...
    開(kāi)封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任良狈,我火速辦了婚禮后添,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘薪丁。我一直安慰自己遇西,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布严嗜。 她就那樣靜靜地躺著粱檀,像睡著了一般。 火紅的嫁衣襯著肌膚如雪漫玄。 梳的紋絲不亂的頭發(fā)上茄蚯,一...
    開(kāi)封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音睦优,去河邊找鬼渗常。 笑死,一個(gè)胖子當(dāng)著我的面吹牛汗盘,可吹牛的內(nèi)容都是我干的皱碘。 我是一名探鬼主播,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼隐孽,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼癌椿!你這毒婦竟也來(lái)了健蕊?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤踢俄,失蹤者是張志新(化名)和其女友劉穎缩功,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體褪贵,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡掂之,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了脆丁。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片世舰。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖槽卫,靈堂內(nèi)的尸體忽然破棺而出跟压,到底是詐尸還是另有隱情,我是刑警寧澤歼培,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布震蒋,位于F島的核電站,受9級(jí)特大地震影響躲庄,放射性物質(zhì)發(fā)生泄漏查剖。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一噪窘、第九天 我趴在偏房一處隱蔽的房頂上張望笋庄。 院中可真熱鬧,春花似錦倔监、人聲如沸直砂。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)静暂。三九已至,卻和暖如春谱秽,著一層夾襖步出監(jiān)牢的瞬間洽蛀,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工疟赊, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留郊供,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓听绳,卻偏偏與公主長(zhǎng)得像颂碘,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 按出題熱度排序: 題號(hào)題目通過(guò)率難度#972相等的有理數(shù)40.90%困難#631設(shè)計(jì)Excel求和公式26.30%...
    婉妃閱讀 3,109評(píng)論 0 1
  • 1.數(shù)組和字符串 “題目怎么說(shuō)头岔,你就怎么做”塔拳,這類題目一般不涉及高深的算法,著重考查的是代碼能力和思維峡竣。 當(dāng)然靠抑,有...
    夢(mèng)想是教小朋友算法閱讀 944評(píng)論 0 1
  • 第1期 中國(guó)風(fēng)墨跡筆刷 第2期 UI設(shè)計(jì)師大禮包 第3期12款懷舊字體 第4期青春文藝范排版 第5期創(chuàng)意幾何立體構(gòu)...
    最新最全設(shè)計(jì)素材閱讀 1,837評(píng)論 0 2
  • 久違的晴天,家長(zhǎng)會(huì)适掰。 家長(zhǎng)大會(huì)開(kāi)好到教室時(shí)颂碧,離放學(xué)已經(jīng)沒(méi)多少時(shí)間了。班主任說(shuō)已經(jīng)安排了三個(gè)家長(zhǎng)分享經(jīng)驗(yàn)类浪。 放學(xué)鈴聲...
    飄雪兒5閱讀 7,523評(píng)論 16 22
  • 創(chuàng)業(yè)是很多人的夢(mèng)想载城,多少人為了理想和不甘選擇了創(chuàng)業(yè)來(lái)實(shí)現(xiàn)自我價(jià)值,我就是其中一個(gè)费就。 創(chuàng)業(yè)后诉瓦,我由女人變成了超人,什...
    亦寶寶閱讀 1,810評(píng)論 4 1