首页 > 编程语言 >初级算法01

初级算法01

时间:2024-06-08 09:22:04浏览次数:19  
标签:01 return 初级 int nums 算法 ++ length num

用时:42min

class Solution {
    public int removeDuplicates(int[] nums) {
        /**
         * 双指针,右指针遍历整个数组,左指针记录有效值
         */
         
        int l = 0, r = 0;
        Set<Integer> s = new HashSet<Integer>();
        for(; r < nums.length; r++){
            if(s.add(nums[r])){
                int t = nums[l];
                nums[l] = nums[r];
                nums[r] = t;
                l++;
            }
        }
        return l;
    }
}

/*优化后版本*/
class Solution {
    public int removeDuplicates(int[] nums) {
        // 非严格递增序列:去除重复元素后的序列是递增的,也就是说重复元素相邻
        int l = 0, r = 0;
        for(; r < nums.length; r++){
            // 让左指针位置的元素是符合条件的,右指针一直向后遍历
            // 换句话说就是让左指针后面的相邻元素不与左指针元素重复
            if(nums[l] != nums[r]){
                nums[l + 1] = nums[r];
                l++;
            }
        }
        return l + 1;
    }
}


用时: 17min

class Solution {
    public int maxProfit(int[] prices) {
        // 当天买卖无收益,计算相邻两天的正收益之和 [贪心算法:通过局部最优解实现整体最优]
        // 假如是第一天买,第三天卖 (d3 - d1) = (d3 - d2) + (d2 - d1)
        int profit = 0;
        for(int i = 1; i < prices.length; i++){
            // profit += prices[i] - prices[i - 1] > 0 ? prices[i] - prices[i - 1] : 0;
            profit += Math.max(0, prices[i] - prices[i - 1]);
        }
        return profit;
    }
}


用时:38min

class Solution {
    public void rotate(int[] nums, int k) {
        /**
            先整体翻转,再局部翻转
         */
        k %= nums.length;
        convertNums(nums, 0, nums.length - 1);
        convertNums(nums, 0, k - 1);
        convertNums(nums, k, nums.length - 1);
    }
    public void convertNums(int [] nums, int l , int r){
        while(l < r){
            int t = nums[l];
            nums[l] = nums[r];
            nums[r] = t;
            l++;
            r--;
        }
    }
}


用时:5min

class Solution {
    public boolean containsDuplicate(int[] nums) {
        // 占用额外内存
        Set<Integer> s = new HashSet<>();
        for(int num : nums){
            if(!s.add(num)){
                return true;
            }
        }
        return false;

        // 慢
        // Arrays.sort(nums);
        // for(int i = 1; i < nums.length; i++){
        //     if(nums[i - 1] == nums[i]){
        //         return true;
        //     }
        // }
        // return false;
    }
}


用时: 26min

class Solution {
    public int singleNumber(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }
        Arrays.sort(nums);
        int t = nums[0];
        int p = -1;
        for(int i = 1; i < nums.length; i++){
            if(nums[i] == p){
                continue;
            }

            if(t == nums[i] && t != p){
                p = nums[i];
                t = -1;
            }else{
                t = t == -1 ? nums[i] : t;
            }


        }
        return t;
    }
}

/* 优化版本 */
class Solution {
    public int singleNumber(int[] nums) {
        // 位运算(异或运算,相同为零、不同为1, 0 ^ n = n,所以最后就剩下那个唯一的元素)
        if(nums.length == 1){
            return nums[0];
        }
        int result = 0;
        for(int num : nums){
            result ^= num;
        }
        return result;
    }
}


用时: 32min

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        // 散列桶计数
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int num : nums1){
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        int [] result = new int[nums1.length < nums2.length ? nums1.length : nums2.length];
        int index = -1;
        for(int num : nums2){
            int count = map.getOrDefault(num, 0);
            if(count > 0){
                result[++index] = num;
                map.put(num, count - 1);
            }
        }
        return Arrays.copyOfRange(result, 0, index + 1);
    }
}


用时: 33min

class Solution {
    public int[] plusOne(int[] digits) {
        int len = digits.length;
        boolean last = false;
        for(int i = len - 1; i >= 0; i--){
            int num = digits[i] + 1;
            if(num < 10){
                digits[i] = num;
                break;
            }else{
                digits[i] = num - 10;
            }
            if(i == 0){
                last = num > 9;
            }
        }
        int [] arr = last ? new int[digits.length + 1] : new int[digits.length];
        if(last){
            arr[0] = 1;
            System.arraycopy(digits, 0, arr, 1, digits.length);
            return arr;
        }else{
            return digits;
        }
    }
}

/* 优化版本 */
class Solution {
    public int[] plusOne(int[] digits) {
        for(int i = digits.length - 1; i >= 0; i--){
            int num = digits[i] + 1;
            digits[i] = num % 10;
            if(num < 10){
                return digits;
            }
        }
        digits = new int[digits.length + 1];
        // 为什么之赋值一个就够了呢?因为原数组空间不够的情况只能是数值为 10000(n个零)
        digits[0] = 1; 
        return digits;
    }
}


用时:5min

class Solution {
    public void moveZeroes(int[] nums) {
        int l = 0, r = 0;
        while(r < nums.length){
            if(nums[r] != 0){
                int t = nums[l];
                nums[l] = nums[r];
                nums[r] = t;
                l++;
            }
            r++;
        }
    }
}


用时:9min

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            int num = target - nums[i];
            int idx = map.getOrDefault(num, -1);
            if(idx != -1){
                return new int[]{idx, i};
            }
            map.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
}


用时:20min

class Solution {
    public boolean isValidSudoku(char[][] board) {
        int [][] row = new int[9][9];
        int [][] column = new int[9][9];
        int [][][] block = new int[3][3][9];

        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[0].length; j++){
                if(board[i][j] == '.'){
                    continue;
                }
                int idx = board[i][j] - '0' - 1; // 数值要转化成对应索引,所以需要减一
                row[i][idx]++;
                column[j][idx]++;
                block[i / 3][j / 3][idx]++;
                if(row[i][idx] > 1 || column[j][idx] > 1 || block[i / 3][j / 3][idx] > 1){
                    return false;    
                }
            }
        }
        return true;

    }
}


用时:15min

class Solution {
    public void rotate(int[][] matrix) {
        /** 先主对角线翻转,然后再左右翻转 */
        int [][] arr = new int[matrix.length][matrix[0].length];
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < i; j++){
                int num = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = num;
            }
        }
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length / 2; j++){
                int num = matrix[i][j];
                matrix[i][j] = matrix[i][matrix[0].length -1 - j];
                matrix[i][matrix[0].length -1 - j] = num;
            }
        }
    }
}

标签:01,return,初级,int,nums,算法,++,length,num
From: https://www.cnblogs.com/20200109-zwh/p/18236473

相关文章

  • 覆盖路径规划经典算法 The Boustrophedon Cellular Decomposition 详解
    2000年一篇论文CoverageofKnownSpaces:TheBoustrophedonCellularDecomposition横空出世,解决了很多计算机和机器人领域的覆盖路径问题,今天我来详细解读这个算法。TheBoustrophedonCellularDecomposition算法详解这篇论文标题为"CoveragePathPlanning:TheB......
  • 算法分析与设计实验一、分治策略实现大整数乘法
    目录实验目的和要求实验环境实验内容与过程 实验内容关键代码 流程图实验结果与分析(实验结果截图)结果分析:实验心得实验目的和要求分治策略实现大整数乘法。设计并使时间复杂度为O(n1.59)。实验环境Windows11Pycharm2021实验内容与过程 实验内容对输入的......
  • C# 链接access数据库 vs2010
    C#链接access数据库vs2010链接access数据库找到你当前以mdb为后缀名的文件,例如""E:\zonghedata_demo.mdb",那么链接的string内容为:"@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+filePath+";"准备好链接字符串后,使用数据类型OleDbConnection来链接打开文件,代码如下......
  • 【BP时序预测】基于鱼鹰算法OOA优化BP神经网络实现温度数据预测算法研究附matlab代码
    以下是一个大致的步骤和MATLAB代码框架:数据准备:准备用于训练和测试的温度数据集。初始化BP神经网络:定义神经网络的结构(如隐藏层的数量和每层的神经元数量)。定义适应度函数:这是优化算法的目标函数,它应该根据神经网络的预测性能(如均方误差MSE)来评估神经网络的权重和偏置。......
  • 解决Docker遇到error NU1301: Unable to load the service index for source https://
    解决Docker容器内无法通过HTTPS访问外部网络的问题在使用Docker构建.NET项目时,有时会遇到无法通过HTTPS访问外部网络的问题,导致dotnetrestore命令无法从NuGet源下载依赖项。本文将介绍一种通过修改Docker配置文件config.json来解决该问题的方法。问题描述在......
  • 同星TSMaster中如何自定义E2E校验算法
    文章目录前言一、自定义E2E算法教程1.定义checksum算法2.定义【CAN预发送事件】3.E2E报文信号仿真4.运行工程二、TSMaster配置E2E教程1.激活仿真报文2.E2E配置三.小结前言最近因项目需要,用到TSMaster进行E2E校验算法实现。第一次使用TSMaster,把整个的过程做一个记......
  • 代码随想录算法训练营第三十一天 | 455.分发饼干 376.摆动序列 53.最大子数组和
    455.分发饼干题目链接文章讲解视频讲解classSolution{public:intfindContentChildren(vector<int>&g,vector<int>&s){sort(g.begin(),g.end());sort(s.begin(),s.end());intindex=0;//从最小的饼干开始遍历f......
  • 算法学习笔记(23):杜教筛
    杜教筛参考来源:OI-Wiki,网上博客线性筛可以在线性时间求积性函数前缀和,而杜教筛可以用低于线性时间求解积性函数前缀和。我们考虑\(S(n)\)就是积性函数的前缀和,所以我们尝试构造关于\(\largeS(n)\)关于\(\largeS(\lfloor\frac{n}{i}\rfloor)\)的递推式。对于任意......
  • m基于PSO粒子群优化的LDPC码NMS译码算法最优归一化参数计算和误码率matlab仿真
    1.算法仿真效果matlab2022a仿真结果如下:     2.算法涉及理论知识概要       低密度奇偶校验码(Low-DensityParity-CheckCode,LDPC码)因其优越的纠错性能和近似香农极限的潜力,在现代通信系统中扮演着重要角色。归一化最小和(NormalizedMin-Sum,NMS)译码......
  • 基于GA-PSO遗传粒子群混合优化算法的DVRP问题求解matlab仿真
    1.程序功能描述       车辆路径问题(VehicleRoutingProblem,VRP)是运筹学领域的一个经典问题,旨在寻找满足一系列送货或取货需求的最优车辆行驶路径。DVRP是一个经典的组合优化问题,在物流配送、运输调度等领域有广泛应用。它要求确定一组最优路径,使得一定数量的车辆从起......