for (int i = start; i < chars.length; i++) { if (chars[i]>='0' && chars[i]<='9') { res = res*10+chars[i]-'0'; if (res>Integer.MAX_VALUE) { return isPositive?Integer.MAX_VALUE :Integer.MIN_VALUE; } } else{ break; } }
if (!isPositive) { res = 0-res; } } return (int)res; } }
classMyStack{ private Queue<Integer> q1 = new LinkedList<>(); private Queue<Integer> q2 = new LinkedList<>(); privateint top; /** Initialize your data structure here. */ publicMyStack(){
} /** Push element x onto stack. */ publicvoidpush(int x){ q2.add(x); top = x; while (!q1.isEmpty()) { q2.add(q1.remove()); } Queue<Integer> temp = q1; q1 = q2; q2 = temp; } /** Removes the element on top of the stack and returns that element. */ publicintpop(){ q1.remove(); int res = top; if (!q1.isEmpty()) { top = q1.peek(); } return res; } /** Get the top element. */ publicinttop(){ return top; } /** Returns whether the stack is empty. */ publicbooleanempty(){ return q1.isEmpty(); } }
/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); int top;
/** Initialize your data structure here. */ publicMyQueue(){
}
/** Push element x to the back of queue. */ publicvoidpush(int x){ if (stack1.empty()) top = x; while (!stack1.isEmpty()) stack2.push(stack1.pop()); stack2.push(x); while (!stack2.isEmpty()) stack1.push(stack2.pop());
}
/** Removes the element from in front of queue and returns that element. */ publicintpop(){ int res = stack1.pop(); if (!stack1.empty()) top = stack1.peek(); return res; }
/** Get the front element. */ publicintpeek(){ return top; }
/** Returns whether the queue is empty. */ publicbooleanempty(){ return stack1.isEmpty(); } }
/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
/** * Initialize your data structure here. */ publicMyQueue(){ stackPush = new Stack<>(); stackPop = new Stack<>(); }
/** * Push element x to the back of queue. */ publicvoidpush(int x){ stackPush.push(x); }
/** * 辅助方法:一次性将 stackPush 里的所有元素倒入 stackPop * 注意:1、该操作只在 stackPop 里为空的时候才操作,否则会破坏出队入队的顺序 * 2、在 peek 和 pop 操作之前调用该方法 */ privatevoidshift(){ if (stackPop.isEmpty()) { while (!stackPush.isEmpty()) { stackPop.push(stackPush.pop()); } } }
/** * Removes the element from in front of queue and returns that element. */ publicintpop(){ shift(); if (!stackPop.isEmpty()) { return stackPop.pop(); } thrownew RuntimeException("队列里没有元素"); }
/** * Get the front element. */ publicintpeek(){ shift(); if (!stackPop.isEmpty()) { return stackPop.peek(); } thrownew RuntimeException("队列里没有元素"); }
/** * Returns whether the queue is empty. */ publicbooleanempty(){ return stackPush.isEmpty() && stackPop.isEmpty(); } }
/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ public List<Integer> inorderTraversal(TreeNode root){ List<Integer> res = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while (p!=null|| !stack.isEmpty()) { while (p!=null) { stack.push(p); p=p.left; }
if (!stack.isEmpty()) { p = stack.pop(); res.add(p.val); p=p.right; } } return res; } }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ //这个pre非常巧妙 long pre = Long.MIN_VALUE; publicbooleanisValidBST(TreeNode root){ if (root==null) { returntrue; } if(!isValidBST(root.left)){ returnfalse; };
if (root.val <= pre) { returnfalse; } pre = root.val; return isValidBST(root.right); } }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if (root==null) { return res; } LinkedList<TreeNode> queue = new LinkedList<>(); queue.add(root); int nextLevel = 0; int toBePrinted = 1; ArrayList<Integer> temp = new ArrayList<>();
while (!queue.isEmpty()) { TreeNode p =queue.pop(); temp.add(p.val); toBePrinted--;
if (p.left!=null) { queue.add(p.left); nextLevel++; }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ public List<List<Integer>> zigzagLevelOrder(TreeNode root) { if (root == null) { returnnew ArrayList<List<Integer>>(); }
List<List<Integer>> results = new ArrayList<List<Integer>>();
// add the root element with a delimiter to kick off the BFS loop LinkedList<TreeNode> node_queue = new LinkedList<TreeNode>(); node_queue.addLast(root); //把null作为结束 node_queue.addLast(null);
LinkedList<Integer> level_list = new LinkedList<Integer>(); boolean is_order_left = true;
while (node_queue.size() > 0) { TreeNode curr_node = node_queue.pollFirst(); if (curr_node != null) { if (is_order_left) level_list.addLast(curr_node.val); else level_list.addFirst(curr_node.val);
if (curr_node.left != null) node_queue.addLast(curr_node.left); if (curr_node.right != null) node_queue.addLast(curr_node.right);
} else { // we finish the scan of one level results.add(level_list); level_list = new LinkedList<Integer>(); // prepare for the next level if (node_queue.size() > 0) node_queue.addLast(null); is_order_left = !is_order_left; } } return results; } }
//发现其实这些 end没啥大用,就是为了好理解 public TreeNode BuildTree(int pStart,int pEnd, int inStart,int inEnd){ //第一个是根节点 TreeNode root = new TreeNode(preorder[pStart]); if (pStart==pEnd) { return root; } int i=inStart; //从中序遍历中找出根节点,将其分开 for (; i <=inEnd; i++) { if (preorder[pStart] == inorder[i]) { break; } } int len = i-inStart; if (pStart+1<=pStart+len) root.left = BuildTree(pStart+1,pStart+len,inStart,i-1); if (pStart+len+1<=pEnd) root.right = BuildTree(pStart+len+1,pEnd,i+1,inEnd); return root; } }
public TreeNode BuildTree(int pStart,int pEnd, int inStart,int inEnd){
//最后一个是根节点 TreeNode root = new TreeNode(postorder[pEnd]); if (pStart==pEnd) { return root; } int i=inStart; //从中序遍历中找出根节点,将其分开 for (; i <=inEnd; i++) { if (postorder[pEnd] == inorder[i]) { break; } } int len = i-inStart; if (pStart<=pStart+len-1) root.left = BuildTree(pStart,pStart+len-1,inStart,i-1); if (pStart+len<=pEnd-1) root.right = BuildTree(pStart+len,pEnd-1,i+1,inEnd); return root; } }
publicclassSolution{ /** * @param m: An integer m denotes the size of a backpack * @param A: Given n items with size A[i] * @return: The maximum size */ publicintbackPack(int m, int[] A){ if(A==null||A.length<=0||m<=0){ return0; } //当前容量下最大值 int []dp = newint[m+1];
for (int i = 0; i < A.length; i++) { //逆序 for (int j = dp.length-1; j >=A[i]; j--) { dp[j] = Math.max(dp[j],dp[j-A[i]]+A[i]); } }
publicclassSolution{ /** * @param m: An integer m denotes the size of a backpack * @param A: Given n items with size A[i] * @param V: Given n items with value V[i] * @return: The maximum value */ publicintbackPackII(int m, int[] A, int[] V){ // write your code here if(A==null||A.length<=0||V==null||V.length<=0||A.length!=V.length||m<=0){ return0; }
//容量 int []dp = newint[m+1];
for (int i = 0; i < A.length; i++) { //逆序遍历 for (int j = dp.length-1; j >=A[i]; j--) { dp[j] = Math.max(dp[j],dp[j-A[i]]+V[i]); } } return dp[m]; } }
publicclassbackPackIII{ /** * @param m: An integer m denotes the size of a backpack * @param A: Given n items with size A[i] * @param V: Given n items with value V[i] * @return: The maximum value */ publicintBackPackIII(int m, int[] A, int[] V){ // write your code here
publicclassSolution{ /** * @param nums: an integer array and all positive numbers * @param target: An integer * @return: An integer */ publicintbackPackV(int[] nums, int target){ // write your code here if(nums==null||nums.length<=0||target<=0){ return0; }
int []dp = newint[target+1]; dp[0] = 1; for (int i = 0; i < nums.length; i++) { //逆序 for (int j = target; j>=nums[i]; j--) { dp[j] += dp[j-nums[i]]; } } return dp[target]; } }
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ classSolution{ public ListNode reverseKGroup(ListNode head, int k){ if (head==null) returnnull; int length = 0; ListNode p =head; while (p!=null && length<k) { p=p.next; ++length; }
// find new tail : (n - k % n - 1)th node // and new head : (n - k % n)th node ListNode new_tail = head; for (int i = 0; i < n - k % n - 1; i++) new_tail = new_tail.next; ListNode new_head = new_tail.next;
classSolution{ public ListNode partition(ListNode head, int x){
// before and after are the two pointers used to create the two list // before_head and after_head are used to save the heads of the two lists. // All of these are initialized with the dummy nodes created. ListNode before_head = new ListNode(0); ListNode before = before_head; ListNode after_head = new ListNode(0); ListNode after = after_head;
while (head != null) {
// If the original list node is lesser than the given x, // assign it to the before list. if (head.val < x) { before.next = head; before = before.next; } else { // If the original list node is greater or equal to the given x, // assign it to the after list. after.next = head; after = after.next; }
// move ahead in the original list head = head.next; }
// Last node of "after" list would also be ending node of the reformed list after.next = null;
// Once all the nodes are correctly assigned to the two lists, // combine them to form a single list which would be returned. before.next = after_head.next;
return before_head.next; } }
反转链表II
问题描述
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明: 1 ≤ m ≤ n ≤ 链表长度。
示例:
1 2
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ classSolution{ public ListNode reverseBetween(ListNode head, int m, int n){ if (head==null) { returnnull; } //哑节点 ListNode dummy = new ListNode(-1); dummy.next = head;
publicclasstest1{ publicstaticvoidmain(String[] args){ String a = new String("ab"); // a 为一个引用 String b = new String("ab"); // b为另一个引用,对象的内容一样 String aa = "ab"; // 放在常量池中 String bb = "ab"; // 从常量池中查找 if (aa == bb) // true System.out.println("aa==bb"); if (a == b) // false,非同一对象 System.out.println("a==b"); if (a.equals(b)) // true System.out.println("aEQb"); if (42 == 42.0) { // true System.out.println("true"); } } }
简单的来说:String 类中使用 final 关键字修饰字符数组来保存字符串,private final char value[],所以String 对象是不可变的。
在java8中,String 的实现
1 2 3 4 5 6
publicfinalclassString implementsjava.io.Serializable, Comparable<String>, CharSequence{ /** The value is used for character storage. */ privatefinalchar value[]; }