每日刷题 五月集训 第 3 天 - Sorting

本文详细解析了四道LeetCode排序相关的算法题,包括977. Squares of a Sorted Array、268. Missing Number、1877. Minimize Maximum Pair Sum in Array 和950. Reveal Cards In Increasing Order,通过解题思路和代码实现,阐述如何在排序过程中优化算法复杂度,以达到最小化最大对和的目标。

977. Squares of a Sorted Array

题目介绍:

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

解题思路:

  • Arrays.sort() 的time complexity是 O(n log n)。
  • 更好的sorting解法可以只遍历一遍 O(n), 需要 two pointer 比较array两端数字。

注意的地方 & 须记住的地方:

  • 思考是否需要其他更为efficent的sort方法。这道题的2 pointer很典型。

代码部分:

class Solution {
    public int[] sortedSquares(int[] nums) {
        
        int[] arr = new int[nums.length];
        
        if(nums.length == 0 ){
            return arr;
        }
        
        int left = 0;
        int right = nums.length -1;
        int idx = nums.length-1;
        
        while(left<= right){
            
            if(Math.abs(nums[left]) >= Math.abs(nums[right])){
                arr[idx--] = nums[left]*nums[left];
                left++;
            }else if(Math.abs(nums[left]) < Math.abs(nums[right])){
                arr[idx--] = nums[right]*nums[right];
                right--;
            }
        }
        
        return arr;
    }
}

**Time Complexity and Space Complexity: **

  • Time Complexity: O(n)
  • Space Complexity: O(n)

268. Missing Number

题目介绍:

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

解题思路:

  • 开始的方法是先给Input Array 排序, 然后查找那个缺失的数字。 (排序+遍历array一遍)
  • 之后发现要想提升效率就不一定非要先给array排序,如果要只遍历一遍找到结果的话那么可以使用积累的Sum和数学算法公式 -sum = len * (len + 1) /2。

注意的地方 & 须记住的地方:

标记文本

代码部分:

class Solution {
    public int missingNumber(int[] nums) {
        
        if(nums.length == 0 ){
            return 0;
        }
        int len = nums.length; 
        int sum = len * (len + 1) /2;
        int sum2 = 0;
        for(int i : nums){
            sum -= i;
        }
        return sum;
    }
}

**Time Complexity and Space Complexity: **

  • Time Complexity: O(n)
  • Space Complexity: O(1)

1877. Minimize Maximum Pair Sum in Array (Medium)

题目介绍:

The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.

For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.
Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:

Each element of nums is in exactly one pair, and
The maximum pair sum is minimized.
Return the minimized maximum pair sum after optimally pairing up the elements.

解题思路:

  • 在找出全部的Pair之前先思考Pair Sum的特性,最大的Pair Sum有很多但是题目说要minimized Pair Sum,就要考虑如何在每一次在Array配对中找到maximum pair Sum 然后从中挑最小的。之后发现sort nums的必要性, 只要sort一次之后把每个 min+max 得出然后比较就能生成最小的pair Sum。(当然之后如果要优化结果可能不能用sort。)

  • min <= x <= max, min <=y <= max, 所以 max( min+max, x+y) <= max(min +x, y+ max)

  • 比较每个 min + max的大小就可以获得最小的最大值pair Sum

注意的地方 & 须记住的地方:

  • 仔细读题,思考题目让你思考的Array pairs的特性。

代码部分:

class Solution {
    public int minPairSum(int[] nums) {
      
        if(nums.length == 0){
            return 0;
        }
        Arrays.sort(nums);
        int res = 0;
        int left = 0;
        int right = nums.length-1;
        
        for(int i = 0; i< nums.length; i++){
            res = Math.max(res, nums[left] + nums[right]);
            left++; 
            right--;
        }     
        return res;
    }
}

**Time Complexity and Space Complexity: **

  • Time Complexity: O(n log n)
  • Space Complexity: O(n)

因为Java的Arrays.sort() 的Complexities是这样。

950. Reveal Cards In Increasing Order (Medium)

题目介绍:
You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].

You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.

You will do the following steps repeatedly until all cards are revealed:

Take the top card of the deck, reveal it, and take it out of the deck.
If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.

Note that the first entry in the answer is considered to be the top of the deck.

解题思路:

  • 我个人感觉这道题比前面几道题简单许多,当手写出来给的example是怎么生成的之后就能发现应该是要倒推回去。

注意的地方 & 须记住的地方:

  • Deque的用法之前不大熟悉,要记住:
    •   new ArrayDeque<>()
      
    • for(Iterator i = deque.iterator(); i.hasNext()😉{} 可以用iterator遍历每个object element

代码部分:

class Solution {
    
    
    public int[] deckRevealedIncreasing(int[] deck) {
        int[] res = new int[deck.length];
        if(deck.length == 0 ){
            return res;
        }
        Arrays.sort(deck);
        Deque<Integer> deque = new ArrayDeque<>();
        for(int i = deck.length-1; i >= 0 ; i--){  
            if(deque.size() != 0){
                int num = deque.removeLast();
                deque.addFirst(num);
            }
            deque.addFirst(deck[i]);
        }
        int count = 0;
        for(Iterator<Integer> i = deque.iterator(); i.hasNext();){
            res[count++] = i.next();
        }
        return res;
    }
}

**Time Complexity and Space Complexity: **

  • Time Complexity: O(n log n ) 注意这里用到了Arrays.sort()
  • Space Complexity: O(n)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值