摘要: 第一种算法,不需要任何排序的暴力算法,一个字符一个字符,一个字符串一个字符串去比较,时间复杂度O(m*n), m是数组长度,n是最短字符串的长度。 public String longestCommonPrefix(String[] strs) { StringBuilder res = new S 阅读全文
posted @ 2022-01-25 06:58 阳光明媚的菲越 阅读(24) 评论(0) 推荐(0) 编辑
摘要: 这道题是一道Graph题目,关于这种人际关系网,谁认识不认识谁的题目,用indegree,outdegree是没问题的,时间复杂度是O(n2): /* The knows API is defined in the parent class Relation. boolean knows(int a 阅读全文
posted @ 2022-01-25 03:22 阳光明媚的菲越 阅读(24) 评论(0) 推荐(0) 编辑
摘要: 这道题有两种解法,第一解法,很好理解,利用HashSet,时间复杂度O(n). public String longestWord(String[] words) { Arrays.sort(words); Set<String> set = new HashSet<>(); String res 阅读全文
posted @ 2022-01-24 14:11 阳光明媚的菲越 阅读(18) 评论(0) 推荐(0) 编辑
摘要: 这道题,最重要的是要能观察出,连续的0和连续的1之间的关系——每一组连续的0和连续的1可以贡献出:Math.min(连续0,连续1) 下面的两个算法都可以beat 100%,时间复杂度O(n). public int countBinarySubstrings(String s) { int res 阅读全文
posted @ 2022-01-20 04:57 阳光明媚的菲越 阅读(22) 评论(0) 推荐(0) 编辑
摘要: 这道题的最简单的算法如下,时间复杂度O(m*n) public int countNegatives(int[][] grid) { int res = 0; for(int i=0;i<grid.length;i++){ for ( int j=0;j<grid[0].length;j++){ i 阅读全文
posted @ 2022-01-20 04:23 阳光明媚的菲越 阅读(38) 评论(0) 推荐(0) 编辑
摘要: 这道题最简单的思路是用三个set,把三个数组的数放在set中,然后检查set1中的每个数是不是在set2和set3中,但是这样做的缺点是,set不是sorted的,最后要对结果排序,时间复杂度最坏情况是O(nlogn) (n是三个数组中的最小长度). public List<Integer> arr 阅读全文
posted @ 2022-01-19 08:48 阳光明媚的菲越 阅读(22) 评论(0) 推荐(0) 编辑
摘要: 这道题的最简单算法,时间复杂度O(nlogn): public List<Integer> targetIndices(int[] nums, int target) { Arrays.sort(nums); List<Integer> res = new ArrayList<>(); for(in 阅读全文
posted @ 2022-01-19 05:16 阳光明媚的菲越 阅读(78) 评论(0) 推荐(0) 编辑
摘要: 如果能明确的确定要返回的值是什么,用三个判断,用下面这套模版,例如 704. Binary Search: public int search(int[] nums, int target) { int l=0, r = nums.length-1, mid=0, res = -1;while(l< 阅读全文
posted @ 2022-01-18 15:44 阳光明媚的菲越 阅读(35) 评论(0) 推荐(0) 编辑
摘要: 这道题如果用暴力解法做非常简单,但是题目有要求:Your solution must run in O(log n) time and O(1) space. 如果看到时间复杂度O(logn),那么就一定要想到binary search。需要注意的是,在做这类找数题的时候,一定要看清楚是让返回ind 阅读全文
posted @ 2022-01-18 15:29 阳光明媚的菲越 阅读(12) 评论(0) 推荐(0) 编辑
摘要: 这道理一点没有弯弯绕绕,直接告诉你考binary search,那咱也不客气了,直接上算法,beat 100%,时间复杂度就不用啰嗦了。 public int search(int[] nums, int target) { int l=0, r = nums.length-1, mid=0; wh 阅读全文
posted @ 2022-01-18 14:32 阳光明媚的菲越 阅读(15) 评论(0) 推荐(0) 编辑