1、无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
/**
* 通过下标,记录每个元素出现的位置,对字符串的无重复子串长度进行两两比较
*/
class Solution {
public static int lengthOfLongestSubstring(String s) {
// 记录字符上一次出现的位置
int[] last = new int[128];
for(int i = 0; i < 128; i++) {
last[i] = -1;
}
int n = s.length();
int res = 0;
int start = 0; // 字符串截取子串长度的初始位置
for(int i = 0; i < n; i++) {
// 字符的ASCII码
int index = s.charAt(i);
// last[index]是字符的上一次出现的位置,+1是因为子串中字符不可重复,所以要从上次位置的下一位置开始
start = Math.max(start, last[index] + 1);
// 这里的+1是因为位置记录是从0开始的,计算子串长度要从1开始
res = Math.max(res, i - start + 1);
// 记录字符出现的位置
last[index] = i;
}
return res;
}
2、两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现(每一个元素不能被使用两次)
1、暴力枚举—》时间复杂度O(N^2)
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}
2、使用哈希表—》时间复杂度O(1)
class Solution {
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
// 将数组中的元素放入map集合中
map.put(i, nums[i]);
// 判断map中是否包含target - nums[i]
if (map.containsValue(target - nums[i])) {
return new int[]{nums[i], target - nums[i]};
}
}
return new int[0];
}