Summary:
Suppose we are given with an unsorted array N positive integers.
The array has one number 'A' that is missing and one number 'B' occurs twice in the array.
Through this java code we will find these two numbers in this array.
Solution:
// User function Template for Java class Solve { int[] findTwoElement(int arr[], int n) { // code here int a=0, b=0; // int n = arr.length; for(int i = 0; i < n; i++){ if(arr[Math.abs(arr[i])-1]<0){ a = Math.abs(arr[i]); } else{ arr[Math.abs(arr[i])-1]=-arr[Math.abs(arr[i])-1]; } } for(int i = 0; i < n;i++){ if(arr[i]>0){ b = i+1; break; } } // ArrayList <Integer> ans = new ArrayList<>(); int ans[]=new int[2]; // ans.add(a); // ans.add(b); ans[0]=a; ans[1]=b; return ans; } } |
Explanation:
class Solve { ... }: This is a class named Solve containing a method findTwoElement which takes an array of integers arr and an integer n as input parameters. It returns an array of two integers.
int[] findTwoElement(int arr[], int n) { ... }: This line defines the method signature. It specifies that the method takes an array of integers arr and an integer n as input parameters and returns an array of integers.
int a=0, b=0;: Two integers a and b are initialized to 0. These variables will store the two elements that are repeated in the array.
for(int i = 0; i < n; i++) { ... }: This loop iterates through the elements of the array.
A ) if(arr[Math.abs(arr[i])-1]<0) { ... }: This condition checks if the element at the index equal to the absolute value of the current element minus 1 is negative. If it is, it means that this element has already been encountered before, so it's one of the repeating elements. In this case, we assign the absolute value of the current element to variable a.
B ) else { ... }: If the condition is not met, it means that the current element hasn't been encountered yet. So, we mark its corresponding index in the array as negative by multiplying it by -1.
for(int i = 0; i < n; i++) { ... }: This loop iterates through the array again to find the missing element, which is the one that is still positive.
if(arr[i] > 0) { ... }: This condition checks if the current element is positive. If it is, it means that this element is missing from the array, so we assign i + 1 to variable b.
int ans[]=new int[2];: An array named ans of size 2 is created to store the result.
ans[0]=a; and ans[1]=b;: The repeating elements a and b are assigned to the first and second positions of the ans array respectively.
return ans;: The array ans, containing the repeating elements, is returned as the result of the function.
Answered by:> >samiksha6i4j
Credit:> >Geeksforgeeks
Suggested blogs:
>Step by Step guide to Deploy Terraform in Azure using GitHub Actions
>Testing react components using Hooks and Mocks
>Use Firebase Realtime Database with ASP.NET MVC App
>Use of Singletons in .NET Core in AWS Lambda
>What are common syntax errors and exceptions in Python
>What is data binding in Angular?