当前位置:   article > 正文

leetcode hot 100(刷题篇1)(1/3/2/206/20/19/5/21/34/53)_leetcode hot100刷题顺序

leetcode hot100刷题顺序

目录

1、leetcode1两数之和

2、leetcode3无重复字符的最长子串

3、leetcode2两数相加

4、leetcode206反转链表

5、leetcode20有效的括号

6、leetcode19删除链表的倒数第 N 个结点

7、leetcode5最长回文子串

8、leetcode21合并两个有序链表

9、leetcode34在排序数组中查找元素的第一个和最后一个位置

10、leetcode53最大子数组和


1、leetcode1两数之和

  1. /**
  2. 时间复杂度 O(N²)
  3. 实现思路:我通过俩个for循环,去枚举
  4. */
  5. class Solution {
  6. public int[] twoSum(int[] nums, int target) {
  7. int n = nums.length;
  8. for (int i = 0; i < n; ++i) {
  9. for (int j = i + 1; j < n; ++j) {
  10. if (nums[i] + nums[j] == target) {
  11. return new int[]{i, j};
  12. }
  13. }
  14. }
  15. return new int[0];
  16. }
  17. }
  18. /**
  19. 哈希表的时间复杂度O(1)
  20. 整体的时间复杂度是O(N)
  21. 实现思路: hashtable.containsKey(target - nums[i])
  22. */
  23. class Solution {
  24. public int[] twoSum(int[] nums, int target) {
  25. Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
  26. for (int i = 0; i < nums.length; ++i) {
  27. if (hashtable.containsKey(target - nums[i])) {
  28. return new int[]{hashtable.get(target - nums[i]), i};
  29. }
  30. hashtable.put(nums[i], i);
  31. }
  32. return new int[0];
  33. }
  34. }

2、leetcode3无重复字符的最长子串

  1. /**
  2. 1)当前字符上次的位置
  3. 2)i-1位置往左推的距离
  4. */
  5. class Solution {
  6. public static int lengthOfLongestSubstring(String s) {
  7. if (s == null || s.equals("")) {
  8. return 0;
  9. }
  10. char[] str = s.toCharArray();
  11. // ASCII 只有 0~255
  12. // map[i] = v i这个ascii码的字符,上次出现在V位置
  13. int[] map = new int[256];
  14. for (int i = 0; i < 256; i++) {
  15. map[i] = -1;
  16. }
  17. map[str[0]] = 0;
  18. int N = str.length;
  19. int ans = 1; // 最少长度 1
  20. int pre = 1; // 上一个位置,向左推了多长
  21. for (int i = 1; i < N; i++) {
  22. pre = Math.min(i - map[str[i]], pre + 1);
  23. ans = Math.max(ans, pre);
  24. map[str[i]] = i;
  25. }
  26. return ans;
  27. }
  28. }

3、leetcode2两数相加

  1. /**
  2. 时间复杂度:O(max(m,n))
  3. */
  4. class Solution {
  5. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  6. ListNode head = null; //初始化
  7. ListNode tail = null;
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/966319
推荐阅读
相关标签
  

闽ICP备14008679号