auto commit
This commit is contained in:
@ -2027,6 +2027,8 @@ public int GetUglyNumber_Solution(int N) {
|
|||||||
|
|
||||||
## 解题思路
|
## 解题思路
|
||||||
|
|
||||||
|
最直观的解法是使用 HashMap 对出现次数进行统计,但是考虑到要统计的字符范围有限,因此可以使用整型数组代替 HashMap。
|
||||||
|
|
||||||
```java
|
```java
|
||||||
public int FirstNotRepeatingChar(String str) {
|
public int FirstNotRepeatingChar(String str) {
|
||||||
int[] cnts = new int[256];
|
int[] cnts = new int[256];
|
||||||
@ -2036,6 +2038,30 @@ public int FirstNotRepeatingChar(String str) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
以上的空间复杂度还不是最优的。考虑到最需要找到只出现一次的字符,那么我们只需要统计的次数信息只有 0,1,更大,那么使用两个比特位就能存储这些信息。
|
||||||
|
|
||||||
|
```java
|
||||||
|
public int FirstNotRepeatingChar(String str) {
|
||||||
|
BitSet bs1 = new BitSet(256);
|
||||||
|
BitSet bs2 = new BitSet(256);
|
||||||
|
for (int i = 0; i < str.length(); i++) {
|
||||||
|
char c = str.charAt(i);
|
||||||
|
if (!bs1.get(c) && !bs2.get(c)) { // 0 0
|
||||||
|
bs1.set(c);
|
||||||
|
} else if (bs1.get(c) && !bs2.get(c)) { // 0 1
|
||||||
|
bs2.set(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < str.length(); i++) {
|
||||||
|
char c = str.charAt(i);
|
||||||
|
if (bs1.get(c) && !bs2.get(c)) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
# 51. 数组中的逆序对
|
# 51. 数组中的逆序对
|
||||||
|
|
||||||
## 题目描述
|
## 题目描述
|
||||||
|
Reference in New Issue
Block a user