-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9d6d26f
commit 3be1f17
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
22 changes: 22 additions & 0 deletions
22
Classes/module 6/12 - hasing3/Quesiton/Longest subarr/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,22 @@ | ||
public class Solution { | ||
public int solve(int[] A) { | ||
HashMap<Long, Integer> sumMap = new HashMap<>(); | ||
long cumSum =0; | ||
int maxLength =0; | ||
|
||
for (int i = 0; i < A.length; i++) { | ||
cumSum += A[i]; | ||
|
||
if(cumSum == 0){ | ||
maxLength = i + 1; | ||
} else if(sumMap.containsKey(cumSum)){ | ||
int length = i - sumMap.get(cumSum); | ||
maxLength = Math.max(maxLength, length); | ||
} else { | ||
sumMap.put(cumSum, i); | ||
} | ||
} | ||
|
||
return maxLength; | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
Classes/module 6/12 - hasing3/Quesiton/shaggy/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,16 @@ | ||
public class Solution { | ||
public int solve(int[] A) { | ||
HashMap<Integer, Integer> lastIndexMap = new HashMap<>(); | ||
int minDistance = Integer.MAX_VALUE; | ||
|
||
for (int i = 0; i < A.length; i++) { | ||
if (lastIndexMap.containsKey(A[i])) { | ||
int distance = i - lastIndexMap.get(A[i]); | ||
minDistance = Math.min(minDistance, distance); | ||
} | ||
lastIndexMap.put(A[i], i); | ||
} | ||
|
||
return minDistance == Integer.MAX_VALUE ? -1 : minDistance; | ||
} | ||
} |