349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
List<Integer> l = new ArrayList<Integer>();
Arrays.sort(nums1);Arrays.sort(nums2);
int i=0,j=0;
while(i<nums1.length && j<nums2.length)
{
int temp = nums1[i];
if(temp==nums2[j])
{
if(!l.contains(temp))
l.add(temp);
j++;i++;
}
else if (temp>nums2[j])
j++;
else if(temp<nums2[j])
i++;
}
int[] num =new int[l.size()];
for(i=0;i<l.size();i++)
num[i] = l.get(i);
return num;
}
}
237. Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
, the linked list should become 1 -> 2 -> 4
after calling your function.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
if(node.next!=null)
{
node.val = node.next.val;
node.next = node.next.next;
}
else node = null;
}
}
100. Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
[思路] 虽然烦一些,不过一点一点来就好啦,该判断的就判断。(我昨天发过了,但是网不好没发出去???这草稿也是一段时间之前的好像。。)
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null) return true;
else if(p==null || q==null) return false;
if(p.val != q.val) return false;
boolean flagl = false, flagr = false;
if(p.left!=null && q.left!=null){
flagl = isSameTree(p.left, q.left);
}else if(p.left==null && q.left==null){
flagl = true;
}
if(p.right!=null && q.right!=null){
flagr = isSameTree(p.right, q.right);
}else if(p.right==null && q.right==null){
flagr = true;
}
return flagl & flagr;
}