Leetcode 刷题记录 21 —— 技巧

Leetcode 刷题记录 21 ------ 技巧

本系列为笔者的 Leetcode 刷题记录,顺序为 Hot 100 题官方顺序,根据标签命名,记录笔者总结的做题思路,附部分代码解释和疑问解答,01~07为C++语言,08及以后为Java语言,一共为 01~21,本系列全部结束。

01 只出现一次的数字

java 复制代码
class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for(int num : nums){
            result ^= num;
        }
        return result;
    }
}

位运算

02 多数元素

java 复制代码
class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int n = nums.length;
        int ans = 0;

        for(int num : nums){
            if(!map.containsKey(num)){
                map.put(num, 1);
            }else{
                map.put(num, map.get(num) + 1);
            }
        }

        for(int num : nums){
            if(map.get(num) > (n/2)){
                ans = num;
                break;
            }
        }
        return ans;
    }
}

03 颜色分类

java 复制代码
class Solution {
    public void sortColors(int[] nums) {
        int n = nums.length;
        int ptr = 0;

        //第一次遍历,将0交换到头部
        for(int i=0; i<n; i++){
            if(nums[i] == 0){
                int temp = nums[ptr];
                nums[ptr] = nums[i];
                nums[i] = temp; 
                ptr++;
            }
        }

        //第二次遍历,将1交换到0之后
        for(int i=ptr; i<n; i++){
            if(nums[i] == 1){
                int temp = nums[ptr];
                nums[ptr] = nums[i];
                nums[i] = temp; 
                ptr++;
            }
        }
    }
}

04 下一个排列

java 复制代码
class Solution {
    public void nextPermutation(int[] nums) {
        int len = nums.length;

        //特殊情况判断
        if(nums == null || nums.length < 2){
            return;
        }

        int i = len -2, j = len - 1, k = len - 1;
        while(i >= 0 && nums[i] >= nums[j]){
            i--;
            j--;
        }

        if(i >= 0){
            while(nums[i] >= nums[k]){
                k--;
            }

            int temp = nums[i];
            nums[i] = nums[k];
            nums[k] = temp;
        }

        int left = j, right = len - 1;
        while(left < right){
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }
}
相关推荐
小科先生4 分钟前
Java springboot调用数据库的基本流程
java·数据库·spring boot
赤生云电竞14 分钟前
GPU算力共享平台架构实践:任务分发与资源隔离的关键配置
算法·架构·gpu算力
秋饼1 小时前
GPT-Live 全双工语音 API Java 服务端落地实战:事件协议、会话恢复与生产踩坑
java·ai·技术分享·后端开发
SL_staff1 小时前
为什么企业级自动化不能只靠AI编排?——逻辑引擎在确定性业务场景中的不可替代性
java·开源·产品
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:折半搜索优化子集枚举(Meet in the Middle)解析
c++·python·算法·bfs·信息学竞赛
Pniubi2 小时前
MySQL靠什么实现事务的?事务隔离级别有哪些?
java·数据库·mysql
一条Go2 小时前
OnCall 时段路由:跨午夜、左闭右开与「Local 不是时区」
后端·架构·github
松仔log3 小时前
Kotlin中级——callbackFlow
java·前端·kotlin
知守观4 小时前
同一个团队两套分包:DDD 四层落地后,domain 层最大的类还是 5885 行
java·后端·领域驱动设计
Oneshot4 小时前
DLX(Dancing Links)算法详解:求解数独最快的算法
算法