Preface explains
Algorithm learning, daily brush record.
Subject to connect
Collection of errors
The subject content
The set S contains integers from 1 to n. Unfortunately, because of a data error, one number in the set copies the value of another number in the set, causing the set to lose a number and have a duplicate number.
Given an array nums represents the result of an error in set S.
Find the duplicate integers, find the missing integers, and return them as an array.
Example 1:
Input: nums = [1,2,2,4]
Output: [2, 3]
Example 2:
Input: nums = [1,1]
Output: [1, 2]
Tip:
2 <= nums.length <= 10^4
1 <= nums[i] <= 10^4
The analysis process
Note here that the array NUMs is not sequential, so don’t be fooled by the example.
Defines an array that returns results, where the first element holds repeated integers and the second element holds missing integers.
First sort the array NUMs.
Defines the sum sum minus the missing integers. The first integer cannot be repeated. Sum sums the first integer.
Iterating through nums, starting with the second integer, finding repeated integers, and summing up to get the sum minus the missing integers.
If the current integer is equal to the previous integer, find the recurring integer and assign it to the first position in the result array results.
If the current integer is not equal to the previous integer, sum the current elements to sum.
After traversing the array, the missing integer = the sum from 1 to n – minus the sum of the missing integer, which is calculated by the formula: sum = (1 + n) * n / 2, assign the missing integer to the second position of the results array.
The result array results is returned.
To solve the code
Class Solution {public int[] findErrorNums(int[] nums) {class Solution {public int[] findErrorNums(int[] nums) { Int [] results = new int[2]; Sort (nums); Int sum = nums[0]; int sum = nums[0]; For (int I = 1; int I = 1; int I = 1; i < nums.length; ++ I) {if (nums[I] == nums[I]) {// If (nums[I] == nums[I]) {results[0] = nums[I]; } else {sum += nums[I];} else {sum += nums[I]; Results [1] = (1 + nums.length) * nums.length / 2 - sum; results[1] = (1 + nums.length) * nums.length / 2 - sum; // Return results; }}Copy the code
Submit the results
It took 11ms to execute, beating 39.13% of users in time, 40.1MB in memory consumption, and 47.42% in space.
The original link
Original link: A collection of errors