645. Set Mismatch
The set S
originally contains numbers from 1 to n
. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums
representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
Example 1:
Input: nums = [1,2,2,4] Output: [2,3]
Note:
- The given array size will in the range [2, 10000].
- The given array's numbers won't have any order.
题目含义:1到n的等差递增数列,然而给的这个数列,有一个值重复了,也就是多了一个值,少了一个值。任务就是找出多了哪个值,少了哪个值
方法一:
1 public int[] findErrorNums(int[] nums) { 2 int[] res = new int[2]; 3 for (int i : nums) { 4 if (nums[Math.abs(i) - 1] < 0) res[0] = Math.abs(i); 5 else nums[Math.abs(i) - 1] *= -1; 6 } 7 for (int i=0;i<nums.length;i++) { 8 if (nums[i] > 0) res[1] = i+1; 9 } 10 return res; 11 }
方法二:先求出1到n的总和,然后依次做减法
1 public int[] findErrorNums(int[] nums) { 2 Set<Integer> set = new HashSet<>(); 3 int duplicate = 0, n = nums.length; 4 long sum = (n * (n+1)) / 2; 5 for(int i : nums) { 6 if(set.contains(i)) duplicate = i; 7 sum -= i; 8 set.add(i); 9 } 10 return new int[] {duplicate, (int)sum + duplicate}; 11 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!