一定要会的算法繁杂度分析,简直yyds!

小微 科技一定要会的算法繁杂度分析,简直yyds!已关闭评论90字数 850阅读模式
摘要时间复杂度空间复杂度大O符号案例:Two Sumpublic int[] twoSum(int[] nums, int target) { // Solution}public i...

时间繁杂度

空间繁杂度文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

大O符号文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

案例:Two Sum文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

public int[] twoSum(int[] nums, int target) { // Solution}文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length < 2) { return new int[0]; } // TODO: solution here return new int[0];}文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

解法1 Brute Force文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

public int[] twoSum(int[] nums, int target) { if (nums == null || nums.length < 2) { return new int[0]; } for (int i = 0; i < nums.length; i++) { // O(N) int firstNum = nums[i]; // 肯定第一个可能的数字 for (int j = i + 1; j < nums.length; j++) { // O(N) int secondNum = nums[j]; // 肯定第二个可能的数字 if (firstNum + secondNum == target) { return new int[]{firstNum, secondNum}; } } } return new int[0];}文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

解法2 使用HashSet文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

public int[] towSum(int[] nums, int target) { Set<Integer> set = new HashSet<>(); for (int num : nums) { // O(N) int potentialMatch = target - num; if (set.contains(potentialMatch)) { // O(1) return new int[]{potentialMatch, num}; } else { set.add(num); // 空间损耗增添O(1) } } return new int[0];}文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

解法3 使用排序文章源自微观生活(93wg.com)微观生活-https://93wg.com/22135.html

时间-空间的取舍

以上就是微观生活(93wg.com)关于“一定要会的算法繁杂度分析,简直yyds!”的详细内容,希望对大家有所帮助!

继续阅读
 
小微
  • 版权声明: 本文部分文字与图片资源来自于网络,转载此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请立即通知我们(管理员邮箱:81118366@qq.com),情况属实,我们会第一时间予以删除,并同时向您表示歉意,谢谢!
  • 转载请务必保留本文链接:https://93wg.com/22135.html