數(shù)組基礎(chǔ)問題

1.Sum of the array numbers

int sum(int[] nums) {
    int result = 0;
    for (int i = 0; i < nums.length; i++) {
        result += nums[i];
    }
    return result;
}

2.Minimum element of the array

int minimum(int a , int b) {
    if (a < b) {
        return a;
    }
    return b;
}

int minimum(int[] nums) {
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] < min) {
            min = nums[i];
        }
    }
    return min;
}

3.Second minimum element of the array

int secondMinimum(int[] nums) {
    int min = Math.min(nums[0],nums[1]);
    int secondMin = Math.max(nums[0],nums[1]);
    for (int i = 2; i < nums.length; i++) {
        if (nums[i] < min) {
            secondMin = min;
            min = nums[i];
        } else if (nums[i] == min) {
            secondMin = min;
        } else if (nums[i] > min && nums[i] < secondMin) {
            secondMin = nums[i];
        } else if (nums[i] == secondMin) {
            continue;
        } else {
            continue;
        }
    }
    return secondMin;
}

4.Reverse Array

//雙指針噪叙,前后交換
public void reverseArray(int[] nums) {
    int first = 0, end = nums.length - 1;
    while (first < end) {
        swap(nums,first++,end--);
    }
}
private void swap(int[] nums, int first, int second) {
    //注意這里的first和second和上面的區(qū)別伞芹,不同的函數(shù)
    int temp = nums[first];
    nums[first] = nums[second];
    nums[second] = temp;
}

5.Odd Even Sort
奇數(shù)在前里伯,偶數(shù)在后

public void oddEvenSort(int[] nums) {
    int first = 0, second = nums.length-1;
    while (first < second) {
        while (first < second && nums[fisrt] % 2 == 1) {
            first++;//如果是奇數(shù)就跳過繼續(xù)往下遍歷&每次都判斷first < second防止越界
        }
        while (first < second && nums[second] % 2 == 0) {
            second--;
        }
        if (first < second) {
            swap(nums,first++,second--);
        }
    }
}

6.Pivot Sort
找出一個(gè)數(shù),左邊的數(shù)都比他小凳枝,右邊的都比他大


public void pivotSort(int[] nums, int pivot) {
    int first = 0, second = nums.length - 1;
    while (first < second && nums[first] <= pivot) {
        first++;
    }
    while (first < second && nums[second] > pivot) {
        second--;
    }
    if (first < second) {
        swap(nums,first++,second--);
    }
}
public void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

7.Remove Element
前后指針,把要?jiǎng)h除的元素放在最后。first指針從左邊開始數(shù)旱易,不相等就跳過,相等就和右邊不等于目標(biāo)值的元素交換

public int removeElement(int[] nums, int val) {
    if (nums.length == 0) {
        return 0;
    }
    int first = 0, second = nums.length - 1;
    while (first < second) {
        while (first < second && nums[first] != val) {
            first++;
        }
        while (first < second && nums[second] == val) {
            //等于目標(biāo)值就放在最后
            second--;
        }
        if (first < second) {
            swap(nums,first++,second--);
        }
    }
    return return nums[first] != val ? first+1 : first;//例子[3,2,2,3]刪掉3腿堤,考慮first等于second
}
//Solution2 for remvoe element
public int removeElement(int[] nums, int val) {
    int index = 0, len = nums.length;
    //len is the valid length of remaining array
    while (index < len) {
        if (nums[index] == val) {
            len--;//remove one element
            //Keep the possible valid element
            nums[index] = nums[len];
        } else {
            index++;
        }
    }
    return len;
}

8.Merge Two Sorted Array

//粗暴的做法阀坏,兩個(gè)數(shù)組,兩個(gè)指針分別指向數(shù)組的頭地址笆檀,小的放入新的數(shù)組里忌堂,然后最后再把result的數(shù)壓到nums1里。需要額外空間误债。這道題注意是把nums2壓入nums1浸船,而不是生成一個(gè)新的數(shù)組
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] result = new int[m + n];
        int i = 0, j = 0, index = 0;
        while (i < m && j < n) {
            if (nums1[i] < nums2[j]) {
                result[index++] = nums1[i++];
            } else {
                result[index++] = nums2[j++];
            }
        }
        while (i < m) {
            result[index++] = nums1[i++];
        }
        while (j < n) {
            result[index++] = nums2[j++];   
        }
        for (i = 0; i < m + n; i++) {
            nums1[i] = result[i];
        }
        
    }
}

solution:歸并排序,分而治之

class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        result = []
        left, right = 0, 0
        while left < m and right < n:
            if nums1[left] < nums2[right]:
                result.append(nums1[left])
                left += 1
            else:
                result.append(nums2[right])
                right += 1
         #比較完以后肯定有一個(gè)數(shù)組沒有出完       
        while left < m:
            result.append(nums1[left])
            left += 1
        
        while right < n:
            result.append(nums2[right])
            right += 1
            
        for i in range(m + n):
            nums1[i] = result[i]
            
引申:[Sort Integer II]http://www lintcode.com/en/problem/sort-integers-ii/

solution:歸并排序寝蹈,注意這里是在原來數(shù)組基礎(chǔ)上生成了buffer李命,而不是生成新的數(shù)組,注意區(qū)別

class Solution:
    """
    @param A: an integer array
    @return: nothing
    """
    def sortIntegers2(self, A):
        # write your code here
         m = len(A)
         temp = [0 for _ in range(m)]
         self.mergeSort(A, 0, m - 1, temp)
         
    def mergeSort(self, A, start, end, temp):
        if start >= end:
            return 
        
        mid = (start + end) / 2
        #遞歸箫老,分區(qū)間
        self.mergeSort(A, start, mid, temp)
        self.mergeSort(A, mid + 1, end, temp)
        #遞歸完了以后最后要合并兩個(gè)"數(shù)組"封字,這里就是兩個(gè)區(qū)間
        self.merge(A, start, end, temp)
        
    def merge(self, A, start, end, temp):
        mid = (start + end) / 2
        
        left, right = start, mid + 1
        # temp buffer已經(jīng)有了,不能直接append耍鬓,進(jìn)行合并一個(gè)大區(qū)間(不是生成新的數(shù)組)
        index = start
        while left <= mid and right <= end:
            
            if A[left] < A[right]:
                temp[index] = A[left]
                left += 1
                index += 1
            else:
                temp[index] = A[right]
                right += 1
                index += 1
        
        while left <= mid:
            temp[index] = A[left]
            left += 1
            index += 1
            
        while right <= end:
            temp[index] = A[right]
            right += 1
            index += 1
            
        for index in range(start, end + 1):
            A[index] = temp[index]

solution2: 快排阔籽,比歸并排序空間復(fù)雜度更低,不需要額外的數(shù)組牲蜀,注意pivot的選取

class Solution:
    # @param {int[]} A an integer array
    # @return nothing
    def sortIntegers2(self, A):
        # Write your code here
        self.quickSort(A, 0, len(A) - 1)
    
    def quickSort(self, A, start, end):
        if start >= end:
            return
        
        left, right = start, end
        # key point 1: pivot is the value, not the index
        pivot = A[(start + end) / 2]

        # key point 2: every time you compare left & right, it should be 
        # left <= right not left < right
        while left <= right:
            while left <= right and A[left] < pivot:
                left += 1
            
            while left <= right and A[right] > pivot:
                right -= 1
            
            if left <= right:
                A[left], A[right] = A[right], A[left]
                
                left += 1
                right -= 1
        
        self.quickSort(A, start, right)
        self.quickSort(A, left, end)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末笆制,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子涣达,更是在濱河造成了極大的恐慌在辆,老刑警劉巖证薇,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異匆篓,居然都是意外死亡浑度,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門鸦概,熙熙樓的掌柜王于貴愁眉苦臉地迎上來箩张,“玉大人,你說我怎么就攤上這事窗市∠瓤叮” “怎么了?”我有些...
    開封第一講書人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵谨设,是天一觀的道長熟掂。 經(jīng)常有香客問我,道長扎拣,這世上最難降的妖魔是什么赴肚? 我笑而不...
    開封第一講書人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮二蓝,結(jié)果婚禮上誉券,老公的妹妹穿的比我還像新娘。我一直安慰自己刊愚,他們只是感情好踊跟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著鸥诽,像睡著了一般商玫。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上牡借,一...
    開封第一講書人閱讀 51,125評(píng)論 1 297
  • 那天拳昌,我揣著相機(jī)與錄音,去河邊找鬼钠龙。 笑死炬藤,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的碴里。 我是一名探鬼主播沈矿,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼咬腋!你這毒婦竟也來了羹膳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤根竿,失蹤者是張志新(化名)和其女友劉穎陵像,沒想到半個(gè)月后湃缎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蠢壹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了九巡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片图贸。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖冕广,靈堂內(nèi)的尸體忽然破棺而出疏日,到底是詐尸還是另有隱情,我是刑警寧澤撒汉,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布沟优,位于F島的核電站,受9級(jí)特大地震影響睬辐,放射性物質(zhì)發(fā)生泄漏挠阁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一溯饵、第九天 我趴在偏房一處隱蔽的房頂上張望侵俗。 院中可真熱鬧,春花似錦丰刊、人聲如沸隘谣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽寻歧。三九已至,卻和暖如春秩仆,著一層夾襖步出監(jiān)牢的瞬間码泛,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來泰國打工逗概, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留弟晚,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓逾苫,卻偏偏與公主長得像卿城,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子铅搓,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

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

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)瑟押。 張土汪:刷leetcod...
    土汪閱讀 12,743評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,475評(píng)論 0 23
  • 《祀》 / 我們?cè)陉柟庀逻M(jìn)食。 像所有的大型節(jié)日一樣星掰, 人們?cè)陉柟庀录漓胱嫦取?/ 祖先們?cè)陉柟庵?我們?cè)陉柟庵?..
    一畝岐江閱讀 158評(píng)論 1 1
  • 蘭蘭一直生活的很沉重家厌。 和結(jié)婚之前判若兩人。 單身時(shí)椎工,她開朗活潑饭于,對(duì)未來生活充滿美好的想象。 她經(jīng)常和閨蜜憧憬將來...
    阿麗薩閱讀 522評(píng)論 0 0
  • 地鐵上殖熟,不同的人,選擇了不同的生活斑响。 一早的地鐵菱属,人海簇?fù)恚@趟地鐵上的每個(gè)人舰罚,都有自己的打發(fā)方式照皆。 盯著某處,冥...
    塵封的女司機(jī)閱讀 336評(píng)論 0 0