Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-06-28 #282

Open Zheaoli opened 2 years ago

Zheaoli commented 2 years ago

2022-06-28

SaraadKun commented 2 years ago

15. 三数之和

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for(int i = 0; i < n; i++) {
            if (i > 0 && nums[i - 1] == nums[i]) 
                continue;
            int j = i + 1, p = n - 1, target = -nums[i];
            while (j < p) {
                if (j > i + 1 && nums[j - 1] == nums[j]){
                    j++;
                    continue;
                }
                if (nums[j] + nums[p] == target) {
                    ans.add(Arrays.asList(nums[i], nums[j], nums[p]));
                    j++;
                    p--;
                } else if (nums[j] + nums[p] < target) {
                    j++;
                } else {
                    p--;
                }
            }
        }
        return ans;
    }
}

WeChat: Saraad

SaraadKun commented 2 years ago

1647. Minimum Deletions to Make Character Frequencies Unique

class Solution {
    public int minDeletions(String s) {
        int ans = 0;
        int[] cnts = new int[26];
        Map<Integer, Integer> map = new HashMap<>();
        for (char ch : s.toCharArray()) 
            cnts[ch - 'a']++;
        for (int cnt : cnts) {
            int key = cnt;
            while (key > 0 && map.containsKey(key)) 
                key--;
            map.put(key, 1);
            ans += cnt - key;
        }
        return ans;
    }
}

WeChat: Saraad

dreamhunter2333 commented 2 years ago
#include <vector>
#include <algorithm>
using namespace std;
/*
 * @lc app=leetcode.cn id=324 lang=cpp
 *
 * [324] 摆动排序 II
 */

// @lc code=start
class Solution
{
public:
    void wiggleSort(vector<int> &nums)
    {
        int n = nums.size();
        vector<int> arr = nums;
        sort(arr.begin(), arr.end());
        int x = (n + 1) / 2;
        int j = x - 1, k = n - 1;
        for (size_t i = 0; i < n; i += 2)
        {
            nums[i] = arr[j];
            if (i + 1 < n)
                nums[i + 1] = arr[k];
            j -= 1;
            k -= 1;
        }
    }
};
// @lc code=end

微信id: 而我撑伞 来自 vscode 插件