2,Array
(1)How to implement Java ArrayList
public class ArrayList { private int capacity; private int size; private int[] data; public ArrayList(int capacity_) { capacity = capacity_; size = 0; data = new int[capacity]; } public int get(int index) { if (index < 0 || index >= size) { // throw Exception System.out.println("ArrayIndexOutOfBoundsException: " + index); } return data[index]; } public void set(int index, int value) { if (index < 0 || index >= size) { System.out.println("ArrayIndexOutOfBoundsException: " + index); } data[index] = value; } public void add(int index, int value) { if (index < 0 || index > size) { System.out.println("ArrayIndexOutOfBoundsException: " + index); } if (size == capacity) { resize(); } size++; for (int i = size - 1; i >= index + 1; --i) { data[i] = data[i - 1]; } data[index] = value; } private void resize() { capacity *= 2; int[] tempData = new int[size]; for (int i = 0; i < size; ++i) { tempData[i] = data[i]; } data = new int[capacity]; for (int i = 0; i < size; ++i) { data[i] = tempData[i]; } } public void remove(int index) { if (index < 0 || index >= size) { System.out.println("ArrayIndexOutOfBoundsException: " + index); } size--; for (int i = index; i < size; ++i) { data[i] = data[i + 1]; } } public static void main(String[] args) { int[] a = {1}; System.out.println(a[-1]); } }
(2) Two sum
1. Two Sum My Submissions QuestionEditorial Solution Total Accepted: 247444 Total Submissions: 1017480 Difficulty: Easy 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. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read the above updated description carefully. Subscribe to see which companies asked this question
Analyse: Use the HashMap to save (target - nums[i], i)
public class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; if (null == nums || nums.length == 0) { return res; } HashMap<Integer, Integer> map = new HashMap(); for (int i = 0; i < nums.length; ++i) { if (!map.containsKey(nums[i])) { map.put(target - nums[i], i); } else { res[0] = map.get(nums[i]); res[1] = i; break; } } return res; } } /** * All Error: * 1, Compile Error : Line 20: error: unclosed comment. because the space of ‘*‘‘ and ‘/‘‘ * 2, map.add. carelessness */
1,time complexity:
if the recurrence equation is T(n) = aT(b/n) + n ^ c。 if logb a > c , T(n) = n ^ (logb a) if logb a == c, T(n) = n ^ c * logn if logb a < c , T(n) = n ^ c
Preparing for the intervies of FLAG and USDA
原文:http://www.cnblogs.com/yueyebigdata/p/5606053.html