面试常考算法整理

链表

判断链表是否有环(七牛云)

思想:利用快慢双指针

	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;
    }
}

发布了92 篇原创文章 · 获赞 426 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_41112238/article/details/105590502