Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0291954

Browse files
contains duplicate II
1 parentb396769 commit0291954

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
packageeasy;
2+
3+
importjava.util.HashMap;
4+
importjava.util.Map;
5+
6+
/**219. Contains Duplicate II QuestionEditorial Solution My Submissions
7+
Total Accepted: 69920
8+
Total Submissions: 228733
9+
Difficulty: Easy
10+
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.*/
11+
publicclassContainsDuplicateII {
12+
//pretty straightforward, use a hashmap, key is the number itself, value is the last index that this value appeared in the array
13+
//we can keep updating the value as we move forward, since if the current index minus the last index cannot be smaller than k, then
14+
//the later indices won't even do either. So, we only need to keep one index in the value of the HashMap. Cheers!
15+
publicbooleancontainsNearbyDuplicate(int[]nums,intk) {
16+
Map<Integer,Integer>map =newHashMap();
17+
for(inti =0;i <nums.length;i++){
18+
if(map.containsKey(nums[i])) {
19+
if(i -map.get(nums[i]) <=k)returntrue;
20+
elsemap.put(nums[i],i);
21+
}
22+
elsemap.put(nums[i],i);
23+
}
24+
returnfalse;
25+
}
26+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp