总体思路参考上一篇
例题:
解题方法:
1.遇到字母统计使用hash思想进行统计
2.遇到数字可以使用异或运算
例题一
题目内容:
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = “anagram”, t = “nagaram”
输出: true
示例 2:
输入: s = “rat”, t = “car”
输出: false
说明:
你可以假设字符串只包含小写字母。
解题思路
字母异位词: 长度相同,只是字母的位置不相同
此题字母异位词可以使用一个长为26的数组,第一个单词去hash到数组上加一操作,第二单词减一操作,看最后的计算结果数组中是否还有为一的元素。
public class CharDifferentPostion {
String s = "anagrx", t = "nagara";
int[] flags = new int[26];
public static void main(String[] args) {
System.out.println(new CharDifferentPostion().isSame());
}
public boolean isSame() {
if (s.length() != t.length())
return false;
if (s.length() == 0 && t.length() == 0)
return true;
for (int i = 0; i < s.length(); i++) {
flags[s.charAt(i) - 'a'] += 1;
flags[t.charAt(i) - 'a'] -= 1;
}
for (int flag : flags) {
if (flag == 1)
return false;
}
return true;
}
}
例题二
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
异或运算,相同为0,相异为1
解题方法:
异或
解题思路
使用异或,相同为0,相异位1特性查找唯一值
public class SingleNumber {
public static void main(String[] args) {
int[] a = {1,2,3,4,4,2,3,1,8};
System.out.println(new SingleNumber().singleNumber(a));
}
public int singleNumber(int[] nums) {
for (int i = 1;i< nums.length;i++) {
nums[0] = nums[0] ^ nums[i];
}
return nums[0];
}
}
列题三:
题目内容:
给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
解题方法:
使用双向队列模拟滑动窗口统计最大值
1.优先队列 nlogn ,而且解决不了元素重复的问题,除非用hash
2.双端队列 在插入的过程中比较大小,由于在双端队列的两端查询,插入都是O(1),
- 所以将总的复杂度降低到了o(n),如果单向队列,复杂度就升级为n^2
public class SlideWindow {
public static void main(String[] args) {
twoHeaderQuene();
}
public static void priQueneMethod(){
int k = 3;
Queue<Integer> priorityQueue = new PriorityQueue<Integer>((x,y) -> (y-x));
int[] temp = {1,3,-1,-3,5,3,6,7};
int[] result = new int[temp.length-k+1];
for (int i = 0; i < temp.length; i++) {
if(i < k){
priorityQueue.offer(temp[i]);
if(i==k-1)
result[i-k+1]=priorityQueue.peek();
}else {
priorityQueue.remove(temp[i-k]);
priorityQueue.offer(temp[i]);
result[i-k+1]=priorityQueue.peek();
}
}
System.out.println(Arrays.toString(result));
}
public static void twoHeaderQuene(){
int k = 3;
Deque<Integer> deque = new LinkedList<>();
int[] temp = {1,3,-1,-3,5,3,6,7};
int[] result = new int[temp.length-k+1];
deque.offer(0);
for (int i = 1; i < temp.length; i++) {
if(temp[deque.peekFirst()] < temp[i]){
deque.clear();
deque.offerFirst(i);
}else {
deque.offer(i);
}
if(i>k-2){
result[i-k+1]=temp[deque.peekFirst()];
}
}
System.out.println(Arrays.toString(result));
}
}