Algorithm

Linked List

1.Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Mistakes

  1. null pointer exception. Watch out for x.next.next. This might be null. Don't just simply check for x.next
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null){
            return false;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null){
            if (fast.next == null){
                return false;
            }
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow){
                return true;
            }
            
        }
        return false;
    }
}
View Code

 

2.Swap Nodes in Pairs

Mistakes

  1. Always remember to return
  2. You need ListNode var. DONT forget ListNode
  3. check for empty input
  4. dont forget to assign  dummy.next = head;
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode cur = dummy;
        while (cur.next != null && cur.next.next != null) {
            ListNode first = cur.next;
            ListNode second = cur.next.next;
            first.next = second.next;
            cur.next = second;
            second.next = first;
            cur = first;
        }
        return dummy.next;
    }
}
View Code

 

3. Odd Even Linked List

Mistakes

  1. Think twice before using && or || in while loop. In this ace I use || instead of and
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode odd = head;
        ListNode even = head.next;
        ListNode one = head;
        ListNode two = head.next;
        while (even != null && even.next !=null) {
            odd.next = odd.next.next;
            even.next = even.next.next;
            odd = odd.next;
            even = even.next;
        }
        if (even == null) {
            odd.next = two;
        } else {
            odd.next = two;
        }
        return one;
    }
}
View Code

 

4.Reverse Linked List II

Mistakes

  1. Clearly, mark out the stages on paper before implementing
  2. When you modify due to a mistake, remember to modify all the code.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || m == n || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(-10);
        dummy.next = head;
        int start = m - 1;
        int end = n - m;
        ListNode a = dummy;
        ListNode b;
        ListNode c;
        while (start != 0) {
            a = a.next;
            start--;
        }
        ListNode pre = a;
        a = pre.next;
        ListNode startNode = a;
        b = a.next;
        c = b.next;
        while (end != 0){
            end = end - 1;
            b.next = a;
            if (end > 0) {
                a = b;
                b = c;
                c = c.next;
            }           
        }
        startNode.next = c;
        pre.next = b;
        return dummy.next;
    }
}
View Code

 5.Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

 Mistakes

  1. remember to return dummy.next not head if head might be changed in your code
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return head;
        }
        ListNode dummy  = new ListNode(0);
        int len = 0;
        dummy.next = head;
        ListNode cur = head;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        len = len - n;
        cur = dummy;
        while (len > 0) {
            cur = cur.next;
            len = len - 1;
        }
        cur.next = cur.next.next;
        return dummy.next;
    }
}
View Code

 Array

1.Two Sum

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Two pointer

Mistakes

  1. int[] result = new int[2]; //remember how to initialize array 
  2. array.length not length()
  3. check return statement
  4. Arrays.sort
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] num2 = new int[nums.length];
        num2 = nums.clone();
        Arrays.sort(nums); //arrays
        int[] result = new int[2]; //remember how to initialize array 
        int i = 0;
        int j = nums.length - 1; //array.length
        while (i < j) {
                if (nums[i] + nums[j] < target) {
                    i++;
                } 
                if (nums[i] + nums[j] > target) {
                    j--;
                } 
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    break; // check return statemnt 
                }
        }
        i = 0;
        while (num2[i] != nums[result[0]]) {
            i++;
        }
        result[0] = i;
        i = 0;
        while (num2[i] != nums[result[1]]) {
            i++;
        }
        result[1] = i;
        return result;
    }
}

 

2.Remove Element

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

 Keep all the target to remove in between two pointers

class Solution {
   public int removeElement(int[] nums, int val) {
    int i = 0;
    for (int j = 0; j < nums.length; j++) {
        if (nums[j] != val) {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}
}
View Code

3.3Sum Closest

 For example, given array S = {-1 2 1 -4}, and target = 1.

 The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Mistakes

  1. Arrays.sort(num);
  2. Math.abs(result - target)
  3. remeber the case where target == sum. try to avoid this
class Solution {
    public int threeSumClosest(int[] num, int target) {
        int result = num[0] + num[1] + num[num.length - 1];
        Arrays.sort(num);
        for (int i = 0; i < num.length - 2; i++) {
            int first = i + 1;
            int second = num.length - 1;
            while (first < second) {
                int sum = num[i] + num[first] + num[second];
                if (sum < target) {
                    first++;
                } else{ 
                    second--;
                } 
                if (Math.abs(sum - target) < Math.abs(result - target)) {
                    result = sum;
                }
            }
        }
        return result;
    }
}
View Code

 

4.Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

  1. to copy array do element by element
  2. use mod since k could be > than n
class Solution {
    public void rotate(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        int[] arr = new int[n];
        int newStart = n - k;
        for(int i = 0; i < k; i++) {
            arr[i] = nums[i + newStart];
        }
        for(int i = 0; i < n - k; i++) {
            arr[i + k] = nums[i];
        }
        for (int i = 0; i < nums.length; i++) {
            nums[i] = arr[i];
        }
    }
}
View Code

 

Tree

1.Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

 

   1
 /   \
2     3
 \
  5

 

All root-to-leaf paths are:

["1->2->5", "1->3"]
  1. Use recursion
  2. to use a helper remember to specify type public void search(TreeNode root, String path, List<String> answer)
  3. List<String> answer = new ArrayList<String>();
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> answer = new ArrayList<String>();
        if (root != null) {
            search(root, "", answer);
        }
        return answer;
        
    }
    
    public void search(TreeNode root, String path, List<String> answer) {
        if (root.left == null && root.right == null) {
            answer.add(path + root.val);
        }
        if (root.left != null) {
            search(root.left, path + root.val + "->", answer);
        }
        if (root.right != null) {
            search(root.right, path + root.val + "->", answer);
        }
    }
}
View Code

 

2. Same Tree

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

 

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

 

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

 

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false
  1. remember to compare two node use a.val == b.val
  2. to test for null use the node directly
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
View Code

 

3.Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

 

You should return [1, 3, 4].

  • Queue<TreeNode> q = new LinkedList<>();
  • inverse of BFS
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> results = new ArrayList();
        Queue<TreeNode> q = new LinkedList<>();
        if (root == null) {
            return results;
        }
        q.offer(root);
        while (q.size() != 0) {
            int length = q.size();
            for (int i = 0; i < length; i++) {
                TreeNode cur = q.poll();
                if (i == 0) {
                    results.add(cur.val);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
                if (cur.left != null) {
                    q.offer(cur.left);
                }
            }
        }
        return results;
    }
}
View Code

 

4.Find Largest Value in Each Tree Row

You need to find the largest value in each row of a binary tree.

Example:

Input: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

Output: [1, 3, 9]

 

  • BFS
  • Integer.MIN_VALUE
  • Math.max()
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        List<Integer> res = new ArrayList<Integer>();
        q.offer(root);
        if (root == null) {
            return res;
        }
        
        while (q.size() != 0) {
            int max = Integer.MIN_VALUE;
            int length = q.size();
            for (int i = 0; i < length; i++) {
                TreeNode cur = q.poll();
                max = Math.max(cur.val, max);
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
            res.add(max);
        }
        
        return res;
    }
}
View Code

 

 5.Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

 

Example 1:

    2
   / \
  1   3

Binary tree [2,1,3], return true.

 

Example 2:

    1
   / \
  2   3

Binary tree [1,2,3], return false.

  • DFS use inorder (Traverse left, add, traverse right)
  • remember to include everything used in the function name
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        List<TreeNode> res = new ArrayList<TreeNode>();
        int count = 0;
        inorder(root, res);
        
        for (int i = 0; i < res.size() - 1; i++) {
            TreeNode pre = res.get(i);
            TreeNode lat = res.get(i + 1);
            if (pre.val > lat.val) {
                return false;
            } else if (pre.val == lat.val) {
                return false;
            }
        }
        return true;
    }
    
    public void inorder(TreeNode root, List<TreeNode> res) { //remember to include everthing used in function name
       if(root != null) {
        inorder(root.left, res);
        res.add(root);
        inorder(root.right, res);
}
}
}
View Code

 

 

Recursion

1. Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

  • String[] mapping = new String[] {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
  • int x = Character.getNumericValue(digits.charAt(i));
class Solution {
    public List<String> letterCombinations(String digits) {
        String[] mapping = new String[] {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        List<String> res = new ArrayList<String>();
        List<String> temp = new ArrayList<String>();

        temp.add("");
        if(digits.isEmpty()) return res;
        for (int i = 0; i < digits.length(); i++) {
            int x = Character.getNumericValue(digits.charAt(i));
            String cur = mapping[x];
            for (int k = 0; k < temp.size(); k++) {
                String str = temp.get(k);
                for (int j = 0; j < cur.length(); j++) {
                    char curChar = cur.charAt(j);
                    res.add(str + curChar);
                    
            }
                
            }
            temp = new ArrayList<String>(res);
            res = new ArrayList<String>();
        }
        return temp;
    }
}    
View Code

 

 

 

转载于:https://www.cnblogs.com/nolanqu/p/7669777.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值