按难度排序,每天刷点leetcode题,抄点解法,大部分解答是在leetcode的dicuss中找到的,没有一一引用,抱歉。
242Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,s = "anagram", t = "nagaram", return true.s = "rat", t = "car", return false.
Note:You may assume the string contains only lowercase alphabets.
Ans:
public boolean isAnagram(String s, String t) { if(t.length() != s.length()) return false; if(t.length() == 0 && s.length() == 0) return true; char[] cs = s.toCharArray(); char[] ts = t.toCharArray(); Arrays.sort(cs); Arrays.sort(ts); for(int i = 0; i < cs.length; i++) { if(cs[i] != ts[i]) return false; } return true;}
349Intersection 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.
Ans:
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Set<Integer> intersect = new HashSet<>(); for (int i = 0; i < nums1.length; i++) { set.add(nums1[i]); } for (int i = 0; i < nums2.length; i++) { if (set.contains(nums2[i])) { intersect.add(nums2[i]); } } int[] result = new int[intersect.size()]; int i = 0; for (Integer num : intersect) { result[i++] = num; } return result; }
237Delete 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.
Ans:
public class Solution {
public void deleteNode(ListNode node) {
node.val=node.next.val;
node.next=node.next.next;
}
}
100Same 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.
Ans:
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null){
return true;
}
else if((p==null&&q!=null)||(q==null&&p!=null)){
return false;
}
else if(p.val==q.val){
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
else{
return false;
}
}
}
171.Excel Sheet Column Number Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28
Ans:
public class Solution {
public int titleToNumber(String s) {
int result=s.charAt(0)-'A'+1;
for(int i=1;i<s.length();i++){
result=result*26+(s.charAt(i)-'A'+1);
}
return result;
}
}