-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solution to find Duplicates in array
- Loading branch information
Showing
2 changed files
with
26 additions
and
0 deletions.
There are no files selected for viewing
13 changes: 13 additions & 0 deletions
13
Medium/287. Find Duplicate Number/New Approach/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import java.util.Arrays; | ||
public class Solution { | ||
public int findDuplicate(int[] nums) { | ||
Arrays.sort(nums); | ||
|
||
for(int i=1;i<nums.length;i++){ | ||
if(nums[i]==nums[i-1]) | ||
return nums[i]; | ||
} | ||
return -1; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
### Simplest and Easiest approach to solve | ||
|
||
1. Sort the input array `nums` in ascending order. | ||
|
||
2. Initialize a loop from `i` = 1 to `n` (inclusive), where `n` is the length of the sorted `nums` array. | ||
|
||
3. Within the loop: | ||
|
||
a. Check if `nums[i]` is equal to `nums[i-1]`. | ||
|
||
b. If the condition is true, return `nums[i]` as it is the duplicate element. | ||
|
||
4. If no duplicate is found after the loop completes, return -1 to indicate that there are no duplicates in the array. |