时间繁杂度
空间繁杂度文章源自微观生活(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!”的详细内容,希望对大家有所帮助!
评论