1. 程式人生 > 其它 >Leetcode 1046. 最後一塊石頭的重量(Java實現 超詳細註釋!)

Leetcode 1046. 最後一塊石頭的重量(Java實現 超詳細註釋!)

技術標籤:Leetcodeleetcode

Leetcode 1046. 最後一塊石頭的重量

兩種方法!加了詳細的註釋,方便日後複習,也希望能幫到其他小夥伴,如有錯誤,歡迎指正!

Java實現:

class Solution {
    // 方法1:邏輯刪除+尋找最大值法;時間擊敗100%
    public int[] getMaxAndIndex(int[] stones){
        // 該方法功能:輸入一個數組,返回陣列中的最大值及其索引構成的陣列
        int[] res = new int[2];
        int tmp = 0;
        int index =
-1; for (int i = 0; i < stones.length; i++){ if (res[0] < stones[i]){ res[0] = stones[i]; res[1] = i; } } return res; } public int lastStoneWeight(int[] stones) { // 記錄當前石頭剩餘的總數 int n = stones.length;
// 當元素個數大於1就不斷地遍歷 while (n > 1){ // 獲取最大值和索引,並將該索引的值置0,相當於邏輯刪除,因為0一定是陣列中最小的 int[] MaxAndIndex1 = getMaxAndIndex(stones); int max1 = MaxAndIndex1[0]; stones[MaxAndIndex1[1]] = 0; // 獲取第二大的值及索引,並將該索引的值置0,相當於邏輯刪除,因為0一定是陣列中最小的 int
[] MaxAndIndex2 = getMaxAndIndex(stones); int max2 = MaxAndIndex2[0]; stones[MaxAndIndex2[1]] = 0; // 如果兩塊石頭一樣重,兩塊都沒了,就直接將石頭的總數-2 if (max1 == max2){ n -= 2; // 如果兩塊石頭不一樣重,那肯定第一塊更重,直接新增一塊新石頭(重量為max1 - max2); // 放在哪裡都可以,這裡放在了剛取出的第一塊石頭的位置 // 不要忘了這種情況因為加了一塊石頭,石頭總數只需要-1即可 }else{ stones[MaxAndIndex1[1]] = max1 - max2; n -= 1; } } // 返回最大元素即可,如果沒有元素了,那所有位置都是0,最大值剛好也是0,直接返回即可 return getMaxAndIndex(stones)[0]; } // 方法2:大頂堆,直接可以用PriorityQueue,但是這種方式需要不斷地排序,效率不算高 public int lastStoneWeight(int[] stones) { // 大頂堆,生成一個最大堆,該資料結構會自動將堆排序; // 我們傳一個lambda表示式,使得堆中第一個元素為堆中的最大值,這樣我們每次poll第一元素就是最大值 PriorityQueue<Integer> pd = new PriorityQueue<Integer>((a,b) -> { return b - a;}); for (int stone : stones){ pd.offer(stone); } // 當元素個數大於1就不斷地取兩塊石頭 while (pd.size() > 1){ // 取出最大的 int max1 = pd.poll(); // 取出第二大的 int max2 = pd.poll(); // 如果大於,那麼就需要再補充一個兩塊石頭重量的差值大小的石頭 if (max1 > max2){ pd.offer(max1 - max2); } } // 如果沒有元素了就返回0,有就說明剩下的就是最後一塊石頭,直接返回即可 return pd.isEmpty() ? 0 : pd.poll(); } }