Shallow copy One method of copying an object is the shallow copy. In that case a new object B is created, and the fields values of A are copied over to B. This is also known as a field-by-field copy, field-for-field copy, or field copy. If the field value is a reference to an object …
Jump Game
This is No.55 in leetcode. The problem description is: "Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index." Here are 4 approaches to the …
Combination Sum
This is a problem in leetcode. To solve this problem, I decide to use recursion on it: class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> rec = new ArrayList<Integer>(); search( candidates, target, res, rec, 0); return res; } private void search(int[] arr, int tar, List<List<Integer>>res, List<Integer>rec, int …
Number of 1 Bits
This is No.191 in LeetCode. This is the best solution I think, easy to understand and has a straight logic: public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int num_one = 0; //001000000010001 while( n > 0 ){ // 00010011 & 00000001 num_one += …
Rotate Array
This is No.189 problem in LeetCode. The problem description is: Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to …
Dynamic Programming
What is Dynamic Programming? Let’s have a look at the definition on Introduction to Algorithm: "Dynamic programming like the divide-and-conquer method, solves problems by combining the solutions to sub-problems. Different from divide-and-conquer, dynamic programming applies when the sub-problems overlap — that is, when sub-problems share sub-sub-problems. A dynamic programming algorithm solves each sub-sub-problems just once …
Convert Sorted Array to Binary Search Tree
This is NO.108 problem in leetcode. The description of this problem is: Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ …
Continue reading “Convert Sorted Array to Binary Search Tree”
Symmetric Tree – recursion and iteration
This is No.101 problem in leetcode. The question is: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 1.Recursion: Recursion occurs when a thing is defined in terms of itself or of its type. In this problem, I will solve it in recursion first. The thought is …