Leetcode bitmap算法题目 Two Sum 解析
原题通过答案:
import java.util.Hashtable;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] b=new int[2];
Hashtable<Integer,Integer> ht=new Hashtable<Integer,Integer>();
for (int i = 0; i < nums.length; i++) {
ht.put(target-nums[i], target-nums[i]);
}
for (int i = 0; i < nums.length; i++) {
if(ht.containsKey(nums[i])){
for (int j = i+1; j < nums.length; j++) {
if(target-nums[j]==nums[i]){
b[0]=i;
b[1]=j;
return b;
}
}
}
}
return b;
}
}
这个算法无法通过:
/**
* 使用BitMap算法存储元素,目前来看只能存储正整数(不重复)
* 一个int,存储32个数,0-31
* 00001 代表第0位有数字 0
* 00010 代表第1位有数字 1
* 00011 代表第0,1位都有数字 0,1,这就存储了两个数0,1
* 11111 存储了0,1,2,3,4五个整数
* @author Administrator
*
*/
public class BitMapTwoSum {
private static int[] a=new int[1+10000000/32];
public static void main(String[] args) {
int[] nums = {3,2,4};
int[] b=twoSum(nums,6);
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
public static int[] twoSum(int[] nums, int target) {
int[] b=new int[2];
for (int i = 0; i < nums.length; i++) {
set(target-nums[i]);
}
for (int i = 0; i < nums.length; i++) {
if(check(nums[i])>0){
for (int j = i+1; j < nums.length; j++) {
if((target-nums[j])==nums[i]){
b[0]=i;
b[1]=j;
return b;
}
}
}
}
return b;
}
public static void set(int i){
a[i>>5] |= (1<<(i & 31));
}
public static int check(int i){
return a[i>>5] & (1<<(i & 31));
}
}