力扣做题笔记



一、Easy

1 两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target的那两个整数,并返回它们的数组下标。

示例:
输入:nums = [2,7,11,15], target = 9  输出:[0,1]
输入:nums = [3,2,4], target = 6  输出:[1,2]
//暴力枚举法
//时间复杂度:O(N^2)
//空间复杂度:O(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 (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }
}
//哈希表
//时间复杂度:O(N)
//空间复杂度:O(N),其中N是数组中的元素数量。主要为哈希表的开销。
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
        	//hashtable.containsKey判断是否包含target - nums[i]对应的键
            if (hashtable.containsKey(target - nums[i])) {
            	//hashtable.get获得target - nums[i]对应的值
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            //将nums[i]作为键,i作为值放入哈希表中
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}

20 有效的括号

给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。(1) 左括号必须用相同类型的右括号闭合。(2) 左括号必须以正确的顺序闭合。(3) 每个右括号都有一个对应的相同类型的左括号。

示例:
输入:s = "()[]{}"   输出:true
输入:s ="{[]}"   输出:false
//栈方法-栈的特点是先进后出,遍历字符串,遇到左括号压入栈中,遇到右括号从栈顶弹出元素进行匹配
class Solution {
    public boolean isValid(String s) {
        //s长度为奇数时直接排除
        if (s.length() % 2 != 0){
            return false;
        }
        //创建一个栈,用来存放左括号,元素类型是char
        Stack<Character> stack= new Stack<>();
        //遍历s,toCharArray()将字符串转换为字符数组
        for(char ch:s.toCharArray()){
        	//遇到'('、'{'或'['压入栈中,
            if(ch == '('||ch == '{'||ch == '['){
                stack.push(ch);
            }else{
                if(stack.empty()){
                    return false;
                }else{
                	//如果栈不为空,弹出栈顶与右括号进行匹配
                    char temp = stack.pop();
                    if (ch == ')'){
                        if (temp != '('){
                            return false;
                        }
                    }else if(ch == '}'){
                        if (temp != '{'){
                            return false;
                        }
                    }else if(ch == ']'){
                        if (temp != '['){
                            return false;
                        }
                    }
                }
            }
        }
        //三元匹配符,判断遍历结束后是否还有左括号
        return stack.isEmpty() ? true : false;
    }
}

21 合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:
输入:l1 = [1,2,4], l2 = [1,3,4]  输出:[1,1,2,3,4,4]
输入:l1 = [], l2 = []  输出:[]
//迭代
//时间复杂度:O(n + m),其中n和m是两个链表的长度
//空间复杂度:O(1)
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode l3= new ListNode(-1);
        ListNode cur = l3;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        // 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
        cur.next = l1 == null ? l2 : l1;
        return l3.next;
    }
}

27 移除元素

给你一个数组nums和一个值 val,你需要原地移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用O(1)额外空间并原地修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

示例:
输入:nums = [3,2,2,3], val = 3  输出:2, nums = [2,2]
解释:函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2
//双指针法
//时间复杂度:O(n),其中n为序列的长度。我们只需要遍历该序列至多一次。
//空间复杂度:O(1)O(1)O(1)。我们只需要常数的空间保存若干变量。
class Solution {
    public int removeElement(int[] nums, int val) {
    	//设定了左指针和右指针
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            if (nums[left] == val) {
            	//将右指针的值赋予左指正
                nums[left] = nums[right];
                right--;
            } else {
                left++;
            }
        }
        return left;
    }
}

35 搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。请必须使用时间复杂度为 O(logn) 的算法。

示例:
输入: nums = [1,3,5,6], target = 5  输出: 2
class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int ans = nums.length;
        while (left <= right) {
            int mid = (right + left) /2 ;
            if (target == nums[mid]) {
                return mid;  
            } else if (target > nums[mid]){
                right=mid ;
            }else{
                left = mid + 1;
            }
        }
        return nums[left] < target ? left+1:left;
    }
}

二、Medium

2 两数相加

给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储 一位数字。请你将两个数相加,并以相同形式返回一个表示和的链表。

示例:
输入:l1 = [2,4,3], l2 = [5,6,4]  输出:[7,0,8]
解释:342 + 465 = 807.
//迭代法
public class leecode {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(); //创建一个虚拟头节点
        ListNode cur = result; //创建一个当前节点
        int total;
        int next1 = 0;
        while(l1 != null && l2 != null){
            total = l1.val + l2.val + next1;
            cur.next = new ListNode( total % 10 );
            next1 = total / 10;
            cur = cur.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while(l1 != null){
            total = l1.val + next1;
            cur.next = new ListNode( total % 10 );
            next1 = total / 10;
            cur = cur.next;
            l1 = l1.next;
        }
        while(l2 != null){
            total = l2.val + next1;
            cur.next = new ListNode( total % 10 );
            next1 = total / 10;
            cur = cur.next;
            l2 = l2.next;
        }
        if(next1 == 1){
            cur.next = new ListNode(1 );
        }
        return result.next;
    }
//递归法
public class leecode {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int total = l1.val + l2.val;
        int next1 = total / 10;
        ListNode result = new ListNode(total % 10);
        if(l1.next != null || l2.next != null || next1 != 0){
        	//如果l1.next != null,l1 = l1.next,否则l1 = ListNode(0)
            l1 = l1.next != null ? l1.next : new ListNode(0);
            l2 = l2.next != null ? l2.next : new ListNode(0);
            l1.val += next1;
            result.next = addTwoNumbers(l1, l2);
        }
        return result;
    }
    //主函数
    public static void main(String[] args) {
    	//创建一个leecode实例solution
        leecode solution = new leecode();
        //创建列表l1和l2
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        l1.next.next.next = new ListNode(5);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        ListNode l3 = solution.addTwoNumbers(l1, l2);
        while (l3 != null) {
            System.out.print(l3.val + " "); //7,0,8
            l3 = l3.next;
        }
    }
}

22 括号生成

数字n代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且有效的括号组合。

示例:
输入:n = 3   输出:["((()))","(()())","(())()","()(())","()()()"]
//回溯法
class Solution {
    // Leetcode 22. Generate Parentheses
    // Backtracking
    // Time Complexity: Hard To Say
    // Space Complexity: Hard To Say
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        backtracking(n, result, 0, 0, "");
        return result;
    }
    private void backtracking(int n, List<String> result, int left, int right, String str) {
        if (right > left) {
            return;
        }
        //如果右括號和左括號的數量等於n,添加字符串,返回上一步
        if (left == n && right == n) {
            result.add(str);
            return;
        }
        if (left < n) {
            backtracking(n, result, left+1, right, str+"(");
        }
        if (right < left) {
            backtracking(n, result, left, right+1, str+")");
        }
    }
}

24 两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即只能进行节点交换)。

示例:
输入:head = [1,2,3,4]   输出:[2,1,4,3]
输入:head = []   输出:[]
//链表题一般可以先画图,判断节点的指向
//迭代法
//时间复杂度:O(n),其中n是链表的节点数量。需要对每个节点进行更新指针的操作。
//空间复杂度:O(1)
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode result = new ListNode();
        ListNode cur = result; //定义一个当前节点
        //如果链表没有节点或者只有一个节点返回head
        if(head == null || head.next == null){
            return head;
        }
        result.next = head;
        while (cur.next != null && cur.next.next != null){
            ListNode next = head.next;
            ListNode temp = head.next.next;
            cur.next = next;
            head.next = temp;
            next.next = head;
            cur = head;
            head = head.next;
        }
        return result.next;
    }
}
//递归法
//时间复杂度:O(n),其中n是链表的节点数量。需要对每个节点进行更新指针的操作。
//空间复杂度:O(n),其中n是链表的节点数量。空间复杂度主要取决于递归调用的栈空间。
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode next = head.next;
        head.next = swapPairs(head.next.next);
        next.next = head;
`        return next;
    }
}

三、Hard

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值