Leetcode 645(Java)
来源:互联网 发布:jessyline姐妹品牌js 编辑:程序博客网 时间:2024/05/16 17:40
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码如下:
public int[] findErrorNums(int[] nums) { int[] result = new int[2]; int n = nums.length; int sum = n+n*(n-1)/2; int sum1=0; int index=0; boolean[] copy = new boolean[n]; for(int i=0;i<n;i++){ copy[nums[i]-1]=true; sum1+=nums[i]; } for(int i=0;i<n;i++){ if(copy[i]==false){ result[1]=i+1; index=i+1; } } if(sum1>sum){ result[0]=index+sum1-sum; }else{ result[0]=index-(sum-sum1); } return result; }
- Leetcode 645(Java)
- LeetCode 645 : Set Mismatch(java)
- leetcode整理(java)
- Leetcode 543(Java)
- Leetcode 389(Java)
- Leetcode 387(Java)
- Leetcode 207(Java)
- leetcode 49(java)
- Leetcode 463(Java)
- Leetcode 506(Java)
- Leetcode 22(Java)
- Leetcode 151(Java)
- Leetcode 628(Java)
- LeetCode-Java (一)
- Leetcode-Java (二)
- Leetcode-Java (三)
- Leetcode-Java (四)
- Leetcode(java)
- Meteor Shower (bfs)
- 16、反转链表(递归方法)
- 玲珑OJ 1152
- 最长公共子序列
- opencl基础概念
- Leetcode 645(Java)
- 【Python】聚类算法应用 -- 广告投放效果的离线评估
- AJAXday1异步请求编码思路(get请求,验证用户名是否重复)
- 抽象类 接口
- Java Application和Java Applet
- linux基本命令及操作9(软件安装)
- HDU5754(博弈)
- Spring Cloud微服务(3)之网关Zuul
- C