【LeetCode】热题 HOT 100

1. 两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
链接:两数之和
(1)两重循环,暴力求解

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0; i < nums.length; i++) {
            for(int j = i+1; j < nums.length; j++) {
                if(target == nums[i] + nums[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }
}

(2)使用HashMap
解题思路: 遍历数组,查看map中是否存在另一个值与其相加等于target,如果存在则直接返回这两个数值的下标,否则将该值放到map中。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }else {
                map.put(nums[i], i);
            }
        }
        throw new IllegalArgumentException();
    }
}

2. 两数相加

给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字0之外,这两个数都不会以0开头。
链接:两数相加

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int sum = 0, carry = 0;
        while(l1 != null || l2 != null) {
            int x = (l1 != null) ? l1.val : 0;
            int y = (l2 != null) ? l2.val : 0;
            sum = carry + x + y;
            carry = sum / 10;
            if(head == null) {
                head = new ListNode(sum % 10);
                tail = head;
            }else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }
        if(carry > 0) {
          tail.next = new ListNode(carry);  
        }
        return head;
    }
}

3. 无重复字符的最长子串

给定一个字符串s ,请你找出其中不含有重复字符的最长子串的长度。
链接:无重复字符的最长子串

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> set = new HashSet<>();
        int start = 0, end = 0;
        int ans = 0;
        while(start < s.length() && end < s.length()) {
            if(set.contains(s.charAt(end))) {
                set.remove(s.charAt(start));
                start ++;
            }else {
                ans = Math.max(ans, end-start+1);
                set.add(s.charAt(end));
                end ++;
            }
        }
        return ans;
    }
}

49.字母异位词分组(2024.05.29)

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
链接:字母异位词分组
使用HashMap,将每个单词根据字母进行排序并将其作为Map的key

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] chr = str.toCharArray();
            Arrays.sort(chr);
            String str1 = new String(chr);
            if (map.containsKey(str1)) {
                List<String> list = map.get(str1);
                list.add(str);
            } else {
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(str1, list);
            }
        }
        return new ArrayList<List<String>>(map.values());
    }
}

70. 爬楼梯

假设你正在爬楼梯。需要n阶你才能到达楼顶。
每次你可以爬12个台阶。你有多少种不同的方法可以爬到楼顶呢?
链接:爬楼梯

class Solution {
    public int climbStairs(int n) {
        int[] nums = new int[n+1];
        nums[1] = 1;
        if(n<2) return 1;
        else {
            nums[2] = 2;
            for(int i = 3; i <= n; i++) {
                nums[i] = nums[i-1] + nums[i-2];
                }
                return nums[n];
        }
    }
}

94. 二叉树的中序遍历

给定一个二叉树的根节点root,返回它的中序遍历 。
链接:二叉树的中序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        inorder(list, root);
        return list;
    }
    public void inorder(ArrayList<Integer> list, TreeNode root) {
        if(root == null) {
            return ;
        }else {
            inorder(list, root.left);
            list.add(root.val);
            inorder(list, root.right);
        }
    }
}

128. 最长连续序列(2024.05.30)

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
链接:最长连续序列
将数组放进HashSet中去重,每次去查num+i是否在数组中存在,最后的i+1即为该连续序列的长度。重点:为避免重复查询,利用num-1,若num-1不存在,则说明num是序列的第一个值,否则不是可直接跳过。

class Solution {
    public int longestConsecutive(int[] nums) {
        int longestConsecutive = 0;
    	Set<Integer> set = new HashSet<>();
    	for(int num : nums) {
    		set.add(num);
    	}
    	for(int i = 0; i < nums.length; i++) {
    		if(!set.contains(nums[i]-1)) {
    			int longest = 1;
    			while(set.contains(nums[i] + longest)) { //开头
    				longest ++;
    			}
    			longestConsecutive = longestConsecutive > longest ? longestConsecutive: longest;
    		}
    	}
    	return longestConsecutive;
    }
}

283. 移动零(2024.05.31)

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
链接:移动零
每次将不为0的值移到前面,循环结束时前面的值将保持原有的相对顺序,而0则排到最后。即设置i、j两个指针,当i!=0时,交换i和j的值,并将j+1。

class Solution {
    public void moveZeroes(int[] nums) {
    	int j = 0;
    	for(int i = 0; i < nums.length; i++) {
    		if(nums[i] != 0) {
    			int temp = nums[i];
    			nums[i] = nums[j];
    			nums[j] = temp;
    			j++;
    		}
    	}
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值