前言 📢
本日记为个人的刷题学习日记,内容非原创,仅为自己复习知识时,能够看得懂自己写的CV的代码,快速理解题意。另外,👍力扣官方的题解很好用,三叶姐🍭nb!!!!!
821 字符的最短距离
题意
-
给你一个字符串 s
和一个字符 c
,且 c
是 s
中出现过的字符。
-
返回一个整数数组 answer
,其中 answer.length == s.length
且 answer[i]
是 s
中从下标 i
到离它 最近 的字符 c
的 距离 。两个下标 i
和 j
之间的 距离 为 abs(i - j)
,其中 abs
是绝对值函数。
-
简单说,从字符串s
中找一定出现的字符c
,并且记录s
中每个字符距离c
的最短距离(因为c
可能出现多次),返回记录距离的数组
思路
- 暴力 遍历一遍字符数组,找出该字符
c
的位置,记录为position[]
- 再遍历一遍,计算当前字符与
position
数组中距离的最小值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public int[] shortestToChar(String s, char c) { char[] strs = s.toCharArray(); int len = strs.length;
int[] answer = new int[len]; int[] position = new int[len]; int cnt = 0;
for(int i=0; i < len; i++) { if(strs[i] == c) { position[cnt] = i; cnt++; } }
for(int i = 0; i < len; i++) { int temp = len+1; for(int j=0; j<cnt; j++) { temp = temp > Math.abs(i - position[j]) ? Math.abs(i - position[j]) : temp; } answer[i] = temp; } return answer; } }
|
6041 多个数组求交集
题意
- 给你一个二维整数数组
nums
,其中 nums[i]
是由 不同 正整数组成的一个非空数组,
- 按 升序排列 返回一个数组,数组中的每个元素在
nums
所有数组 中都出现过。
思路
- 由于每个数组中,数字各不相同,因此所有数组中均出现的数字,其出现的次数等于数组个数
- 用哈希表统计所有数字出现的次数,次数等于数组个数的数字,即为我们所要找的
- 将这些数字添加入列表后排序,返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public List<Integer> intersection(int[][] nums) { int row = nums.length; Map<Integer, Integer> cntMap = new HashMap<>(); for(int i=0; i<row; i++) { for(int j=0; j<nums[i].length; j++) { cntMap.put(nums[i][j], cntMap.getOrDefault(nums[i][j], 0) + 1); } } List<Integer> list = new ArrayList<>(); int cnt = 0; for(int y : cntMap.keySet()) { if(cntMap.get(y) == row) { list.add(y); } } Collections.sort(list); return list; } }
|
知识点
剑指 Offer II 119. 最长连续序列
题意
- 给定一个未排序的整数数组
nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
思路
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { public int longestConsecutive(int[] nums) { if(nums.length == 0) { return 0; } if(nums.length == 1) { return 1; } Arrays.sort(nums); int i=0, j=1; int tmpLen = 1, maxLen = 1; while(j < nums.length) { if(nums[i] == nums[j] - 1) { tmpLen++; i++; j++; } else if(nums[i] == nums[j]) { i++; j++; } else { i++; j++; maxLen = tmpLen > maxLen ? tmpLen : maxLen; tmpLen = 1; } } maxLen = tmpLen > maxLen ? tmpLen : maxLen; return maxLen; } }
|