Skip to content

Instantly share code, notes, and snippets.

@BiruLyu
BiruLyu / 1. Two Sum.java
Last active July 27, 2017 23:56
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> bufferMap = new HashMap<Integer,Integer>();
int[] res = new int[2];
for(int i = 0; i< nums.length; i++){
if(bufferMap.containsKey(nums[i])){
res[0] = bufferMap.get(nums[i]);
res[1] = i;
public class NumArray {
private int[] nums;
private int[] BITree;
public NumArray(int[] nums) {
int len = nums.length;
this.nums = nums;
this.BITree = new int[len + 1];
for( int i = 0; i < len; i++){
public class NumMatrix {
private int[][] nums;
private int[][] BITree;
private int m;
private int n;
public NumMatrix(int[][] matrix) {
//if (matrix==null||matrix.length == 0 || matrix[0].length == 0) return;//["NumMatrix"] [[[]]]
if (matrix==null||matrix.length == 0) return;
public 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;
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1 == null && nums2 == null) return 0.0;
int len1 = nums1.length, len2 = nums2.length;
int left = (len1 + len2) / 2;
int right = (len1 + len2) / 2 + 1;
if ((len1 + len2) % 2 != 0) {
return (double)findKth(nums1, 0, nums2, 0, right);
} else {
return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
public class Solution {
public List<String> findRepeatedDnaSequences(String s) {
List<String> res = new LinkedList<String>();
Set<String> explored = new HashSet<String>();
Set<String> repeat = new HashSet<String>();//avoid repetition in res
for( int i = 0; i < s.length() - 9; i++){
String temp = s.substring(i,i + 10);
if(!explored.add(temp) && repeat.add(temp)){
res.add(temp);
public class TwoSum {
Set<Integer> sum;
Set<Integer> num;
TwoSum(){
sum = new HashSet<Integer>();
num = new HashSet<Integer>();
}
// Add the number to an internal data structure.
public void add(int number) {
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() < 1) return 0;
int count = 0, end = 0, start = 0, res = 0;
int[] vector = new int[256];
char[] str = s.toCharArray();
while (end < str.length) {
if (vector[str[end++]]++ == 0) count++;
while (count > 2) {
if (--vector[str[start++]] == 0) count--;
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
class Solution {
public class Solution {
public String countChar(String str){
int[] vector = new int[26];
for(char c : str.toCharArray()){
vector[c - 'a']++;
}
return Arrays.toString(vector);
}
public List<List<String>> groupAnagrams(String[] strs) {