双指针又分为:左右指针,快慢指针,暴力法
左右指针:即一个指针left=0,另一个指针right=nums.length-1。right指针向左移动,减小两数之和,left指针向右移动,增加两数和。
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
class Solution {
public int[] twoSum(int[] nums, int target) {
int a=0;
int b=nums.length-1;
while(a<b){
if(nums[a]+nums[b]<target){
a++;
}
else if(nums[a]+nums[b]>target){
b--;
}
else{
return new int[]{nums[a],nums[b]};
}
}
return new int [0];
}
}
暴力一般是以这种形式开始的,然后根据题目条件编写条件填入
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
}
}
还有这种形式的,只遍历一次但是另一个指针由第一次遍历的特征而确定。
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> dic = new HashMap<>();
int i = -1, res = 0;
for(int j = 0; j < s.length(); j++) {
if(dic.containsKey(s.charAt(j)))
i = Math.max(i, dic.get(s.charAt(j))); // 更新左指针 i
dic.put(s.charAt(j), j); // 哈希表记录