Skip to content

Commit 6237b6e

Browse files
author
Wang Dongxu
committed
feat: add HashSet solution for leetcode #3
1 parent 480fd23 commit 6237b6e

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/com/blankj/easy/_001/Solution.java

+25
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,31 @@ public int[] twoSum(int[] nums, int target) {
3535
return null;
3636
}
3737

38+
// Input array is sorted
39+
// https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
40+
public int[] twoSumOrdered(int[] num, int target) {
41+
int[] indice = new int[2];
42+
if(num == null || num.length < 2) {
43+
return indice;
44+
}
45+
int left = 0;
46+
int right = num.length - 1;
47+
while(left < right) {
48+
int sum = num[left] + num[right];
49+
if(sum == target) {
50+
indice[0] = left;
51+
indice[1] = right;
52+
return indice;
53+
} else if(sum < target) {
54+
left++;
55+
} else {
56+
right--;
57+
}
58+
59+
}
60+
return indice;
61+
}
62+
3863
public static void main(String[] args) {
3964
Solution solution = new Solution();
4065
int[] nums = new int[]{2, 7, 11, 15};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.blankj.medium._003;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
/**
7+
* Created by dash wang on 2/11/18.
8+
* <p>
9+
* HashSet + 双指针 问题
10+
*/
11+
public class HashSetSolution {
12+
public int lengthOfLongestSubstring(String s) {
13+
int len = s.length();
14+
Set<Character> set = new HashSet<>();
15+
int max = 0;
16+
int head = 0, tail = 0;
17+
for (head = 0; head < len; head++) {
18+
// 出现重复, 移动尾指针,直到不重复为止
19+
while (set.contains(s.charAt(head))) {
20+
set.remove(s.charAt(tail));
21+
tail++;
22+
}
23+
set.add(s.charAt(head));
24+
int tempLen = head - tail + 1;
25+
if (tempLen > max) {
26+
max = tempLen;
27+
}
28+
}
29+
return max;
30+
}
31+
32+
public static void main(String[] args) {
33+
HashSetSolution solution = new HashSetSolution();
34+
System.out.println(solution.lengthOfLongestSubstring("abcabcbb"));
35+
System.out.println(solution.lengthOfLongestSubstring("bbbbb"));
36+
System.out.println(solution.lengthOfLongestSubstring("pwwkew"));
37+
System.out.println(solution.lengthOfLongestSubstring("Abcabcbb"));
38+
}
39+
}

0 commit comments

Comments
 (0)