package ygy.test.week6;
/**
* Created by guoyao on 2017/10/7.
*/publicclassMergeSortedArray {publicstaticvoidmain(String[] args) {
}
//从大到小的倒序排序publicstaticvoidmerge(int[] nums1, int m, int[] nums2, int n) {
int i=m-1, j=n-1, k=m+n-1;
while (i>-1 && j>-1) nums1[k--]= (nums1[i]>nums2[j]) ? nums1[i--] : nums2[j--];
while (j>-1) nums1[k--]=nums2[j--];
}
}
Remove Duplicates from Sorted List
package ygy.test.week6;
/**
* Created by guoyao on 2017/10/7.
*/publicclassRemoveDuplicatesfromSortedList {publicstaticvoidmain(String[] args) {
ListNode l1=new ListNode(1);
ListNode l2=new ListNode(1);
ListNode l3=new ListNode(1);
l1.next = l2 ;
l2.next = l3 ;
ListNode new_l1=deleteDuplicates(l1);
System.out.println(" -------------------------- ");
do {
System.out.println(new_l1.val);
new_l1=new_l1.next;
}while (new_l1 != null );
}
publicstatic ListNode deleteDuplicates(ListNode head) {
if (head == null) {
returnnull ;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next = head ;
ListNode tempNode = head ;
int temp = head.val;
head = head.next ;
while (head!= null ) {
if (head.val != temp) {
tempNode = head ;
temp = head.val ;
head = head.next ;
continue;
}
tempNode.next = head.next ;
head = head.next ;
}
return dummyHead.next ;
}
//leetcode answerpublicstatic ListNode deleteDuplicates_2(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
}
/**
* Definition for singly-linked list.
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val=x;
}
}
Same Tree
package ygy.test.week6;
/**
* Created by guoyao on 2017/10/8.
*/publicclassSameTree {publicstaticvoidmain(String[] args) {
}
/**
* Given two binary trees, write a function to check if they are equal or not.
* <p>
* Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
*/publicstaticbooleanisSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) returntrue;
if(p == null || q == null) returnfalse;
if(p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
returnfalse;
}
}
/**
* Definition for a binary tree node.
*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val=x;
}
}
Symmetric Tree
package ygy.test.week6;
/**
* Created by guoyao on 2017/10/8.
*/publicclassSymmetricTree {publicstaticvoidmain(String[] args) {
}
/**
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
* 1
/ \
2 2
/ \ / \
3 4 4 3
*/publicstaticbooleanisSymmetric(TreeNode root) {
return root == null || isSymmetricSameTree(root.left, root.right);
}
publicstaticbooleanisSymmetricSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) returntrue;
if(p == null || q == null) returnfalse;
if(p.val == q.val)
return isSymmetricSameTree(p.left, q.right) && isSymmetricSameTree(p.right, q.left);
returnfalse;
}
}