Leetcode 645(Java)

这是一个关于LeetCode第645题的解决方案,题目涉及找出数组中重复和丢失的数。给定一个数组nums,其中数据因错误而重复一次并丢失一次。通过等差数列求和公式、布尔数组和双重遍历找到这两个数,返回结果数组[重复数, 缺失数]。" 106578023,9492151,LeetCode刷题解析:392. 判断子序列,"['算法', 'LeetCode', 'Java', '字符串处理', '贪心算法']
摘要由CSDN通过智能技术生成

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,则可以认为是一个a1=1,项数为n的等差数列。先用等差数列求和公式计算出正确数组所得之和。再建立一个boolean型的数组用于标记一个元素是否出现过。遍历数组改变所遍历元素在boolean型数组里的对应下标,同时计算当前数组的和。遍历完毕后找出下标为false的元素,+1即为所缺少元素,又比较应得之和与当前数组和可以得出重复元素与缺失元素之间的差距。放入result中即可,ac码如下:

    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值