鏈表
判斷鏈表是否有環(七牛雲)
思想:利用快慢雙指針
public boolean hasCycle(ListNode head) {
if(head==null)
return false;
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow)
return true;
}
return false;
}
尋找鏈表相交結點
思路:雙指針
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p=headA;
ListNode q=headB;
while(p!=q){
p=p==null?headB:p.next;
q=q==null?headA:q.next;
}
return p;
}
字符串
字符串最長公共前綴(趣頭條)
思路:讓第一個字符串作爲最長前綴,依次與後面的字符串比較,每次都更新最長前綴的值
public String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length==0)
return "";
if(strs.length==1)
return strs[0];
String prefix=strs[0];
for(int i=1;i<strs.length;i++){
String str=strs[i];
while(str.indexOf(prefix)!=0){
//找到str和prefix的最長前綴
prefix=prefix.substring(0,prefix.length()-1);
}
}
return prefix;
}
二叉樹
翻轉二叉樹(趣頭條)
思路:翻轉右子樹,賦值給左子樹;翻轉左子樹,賦值給右子樹
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root!=null){
TreeNode right = invertTree(root.right);
TreeNode left = invertTree(root.left);
root.left = right;
root.right = left;
}
return root;
}
}