一、字符串中的第一个唯一字符
1.题目简介
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
(题目来源:力扣)
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
你可以假定该字符串只包含小写字母
2.解决方法
- 计数法
class Solution {
public static int firstUniqChar(String s) {
//单独处理s长度为0的情况
if(s.length()==0) return -1;
int[] map=new int[26];
//先统计每一个字符的数量
for (int i = 0; i < s.length(); i++) {
map[s.charAt(i)-'a']++;
}
//再从字符串第一个开始循环到最后一个数字
//找到第一个不重复的字符,没找到则返回-1
for (int i = 0; i < s.length(); i++) {
if(map[s.charAt(i)-'a']==1) {
return i;
}
}
return -1;
}
}
- LinkedHashMap有序存储字符及它对应的个数
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
class Solution {
public static int firstUniqChar(String s) {
//单独处理s长度为0的情况
if(s.length()==0) return -1;
//用LinkedHashMap存储字符对应的个数(逻辑有序[这是我们要的],空间有序)
//为了方便,直接将>1的个数赋值为-1
//所以只有两种情况:
//1.个数=1,字符key对应value也是1
//2.个数>1,字符key对应value是-1
LinkedHashMap<Character, Integer> records=new LinkedHashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
if(records.containsKey(s.charAt(i))) {
records.put(s.charAt(i), -1);
}else {
records.put(s.charAt(i), 1);
}
}
Character fc=null;
//循环LinkedHashMap
for (Entry<Character, Integer> entry : records.entrySet()) {
if(entry.getValue()==1) {
//获取第一个不重复的字符
fc=entry.getKey();
break;
}
}
//返回这个字符在字符串的位置
return fc==null?-1:s.indexOf(fc.toString());
}
}
二、丢失的数字
1.题目简介
给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。
进阶:
你能否实现线性时间复杂度、仅使用额外常数空间的算法解决此问题?
(题目来源:力扣(LeetCode))
示例 1:
输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。
示例 2:
输入:nums = [0,1]
输出:2
解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。
示例 3:
输入:nums = [9,6,4,2,3,5,7,0,1]
输出:8
解释:n = 9,因为有 9 个数字,所以所有的数字都在范围 [0,9] 内。8 是丢失的数字,因为它没有出现在 nums 中。
示例 4:
输入:nums = [0]
输出:1
解释:n = 1,因为有 1 个数字,所以所有的数字都在范围 [0,1] 内。1 是丢失的数字,因为它没有出现在 nums 中。
提示:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
nums 中的所有数字都 独一无二
解决方法:
- 位运算
class Solution {
public int missingNumber(int[] nums) {
//将第一个数字、0、n先进行运算
int diff=nums[0]^0^nums.length;
//循环所有数字和下标
for (int i = 1; i < nums.length; i++) {
diff^=nums[i]^i;
}
return diff;
}
}
//或
class Solution {
public int missingNumber(int[] nums) {
//首先赋值0
int diff=0;
for (int i = 0; i < nums.length; i++) {
//循环计算时n总是要比数组下标大1
diff^=nums[i]^(i+1);
}
return diff;
}
}
更多解法:排序、哈希表