leetCode刷题笔记
文章目录
- 1. 把两个有序链表整合成一个新的有序列表
- 2. 两数之和
- 3. 有效括号的字符串
1. 把两个有序链表整合成一个新的有序列表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
package com.example.demo.main.Domain;
import lombok.Data;@Data
public class CommonNode<V> {public V value;public CommonNode next;
}
package com.example.demo.main.algor;
import com.example.demo.main.Domain.CommonNode;public class MergeTwoNodeTest {/*** 题目:将两个有序的链表,整合出一个有序的链表,从小到大*/public static void main(String[] args) {CommonNode commonNode1 = new CommonNode<Integer>();commonNode1.setValue(1);CommonNode commonNode2 = new CommonNode<Integer>();commonNode2.setValue(3);commonNode1.setNext(commonNode2);CommonNode commonNode3 = new CommonNode<Integer>();commonNode3.setValue(2);CommonNode commonNode4 = new CommonNode<Integer>();commonNode4.setValue(4);commonNode3.setNext(commonNode4);CommonNode mergeNode = mergeTwoNodeList(commonNode1, commonNode3);while (mergeNode != null) {System.out.println(mergeNode.getValue());mergeNode = mergeNode.getNext();}}/*** 将两个有序的链表,整合出一个有序的链表,从小到大*/private static CommonNode mergeTwoNodeList(CommonNode commonNode1, CommonNode commonNode2) {CommonNode headNode = new CommonNode();headNode.setValue(-1);CommonNode preNode = headNode;while (commonNode1 != null && commonNode2 != null) {if ((Integer)commonNode1.getValue() < (Integer)commonNode2.getValue()){preNode.setNext(commonNode1);commonNode1 = commonNode1.getNext();} else {preNode.setNext(commonNode2);commonNode2 = commonNode2.getNext();}preNode = preNode.getNext();}if (commonNode1 == null) {preNode.setNext(commonNode2);} else {preNode.setNext(commonNode1);}return headNode.getNext();}
}
2. 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。每种输入只会对应一个答案。但是,数组中同一个元素在答案里不会重复出现。
可以按任意顺序返回答案。
class Solution {public int[] twoSum(int[] nums, int target) {//Map<Integer, Integer> map = new HashMap<>();Map<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};}map.put(nums[i], i);}return new int[0];}
}
3. 有效括号的字符串
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
示例 4:
输入:s = “([)]”
输出:false
class Solution {public boolean isValid(String s) {int n = s.length();if (n % 2 == 1) {return false;}Map<Character, Character> pairs = new HashMap<Character, Character>() {{put(')', '(');put(']', '[');put('}', '{');}};Deque<Character> stack = new LinkedList<Character>();for (int i = 0; i < n; i++) {char ch = s.charAt(i);if (pairs.containsKey(ch)) {//栈顶元素不是当前元素的左括号if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {return false;}//栈顶元素是当前元素的左括号,出栈stack.pop();} else {//入栈stack.push(ch);}}return stack.isEmpty();}
}