-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindMissingAndRepeatedValuesMath.java
More file actions
42 lines (42 loc) · 1.59 KB
/
FindMissingAndRepeatedValuesMath.java
File metadata and controls
42 lines (42 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2]. Each integer appears exactly once except a which appears twice and b which is missing. The task is to find the repeating and missing numbers a and b.
Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b.
Example 1:
Input: grid = [[1,3],[2,2]]
Output: [2,4]
Explanation: Number 2 is repeated and number 4 is missing so the answer is [2,4].
Example 2:
Input: grid = [[9,1,7],[8,9,2],[3,4,6]]
Output: [9,5]
Explanation: Number 9 is repeated and number 5 is missing so the answer is [9,5].*/
import java.util.*;
class FindMissingAndRepeatedValuesMath{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] grid=new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
grid[i][j]=sc.nextInt();
}
}
System.out.print(Arrays.toString(findMissingAndRepeatedValues(grid)));
}
public static int[] findMissingAndRepeatedValues(int[][] grid){
int n=grid.length;
long total=(long) n*n;
long expectedSum=total*(total+1)/2;
long exprectedSquSum=total*(total+1)*(2*total+1)/6;
long actualSum=0,actualSquSum=0;
for(int[] row:grid){
for(int num:row){
actualSum+=num;
actualSquSum+=(long)num*num;
}
}
long diff=actualSum-expectedSum;
long sum=(actualSquSum-exprectedSquSum)/diff;
int repeated=(int)((diff+sum)/2);
int missing=(int)(sum-repeated);
return new int[]{repeated,missing};
}
}