# 剑指offer解题报告(Java版)——和为s的两个数，一串连续数 41

2Sum问题

public void findNumbersWithSum(int[] sortedArray, int number)

{

if(sortedArray==null)

return ;

int pointEnd=sortedArray.length-1;

{

if(curSum==number)

{

System.out.println(sortedArray[pointEnd]);

break;

}

else

{

if(curSum>number)

pointEnd--;

else

}

}

}

int[] array={1,2,4,7,7,8,8,11,15};

if (pointEnd<sortedArray.length-1&&sortedArray[pointEnd]==sortedArray[pointEnd+1]) {

pointEnd--;

continue;

}

continue;

}

3Sum问题

public static ArrayList threeSum(int[] num) {

Arrays.sort(num);

ArrayList result = new ArrayList();

Map hm = new HashMap();

for (int firstPos = 0; firstPos < num.length; firstPos++) {

int secPos = firstPos + 1;

int thirdPos = num.length - 1;

while (secPos < thirdPos) {

if (num[firstPos] + num[secPos] + num[thirdPos] == 0) {

ArrayList<Integer> midResult = new ArrayList<Integer>();

hm.put(midResult, false);

secPos += 1;

thirdPos -= 1;

} else if (num[firstPos] + num[secPos] + num[thirdPos] < 0) {

secPos += 1;

} else {

thirdPos -= 1;

}

}

}

Iterator it = hm.entrySet().iterator();

while (it.hasNext()) {

//                        Entry entry =(Entry) it.next();

}

return result;

}

2Sum3Sum的时间复杂度分析

3Sum_close问题

close问题需要维护一个距离dis，也就是得到的和与真实想要的和之间的误差，如果新的比旧的小，则更新结果，另外还要维护一个真实的和ret

int dis = Integer.MAX_VALUE;

int ret = 0;

int sum = num[i] + num[j] + num[k];

int minus = sum - target;

int d = Math.abs(minus);

if (d < dis) {

dis = d;

ret = sum;

}

if (minus == 0)

return target;

if (minus < 0) {

j++;

} else {

k--;

}

4sumhash算法

int small=1;

int big=2;

curSum可以用求和公式求出来(small+big)/2

while(small<(s+1)/2)

{

int curSum=0;

for(int i=small;i<=big;i++)

curSum+=i;

if(curSum==s)

{

System.out.println("find one");

for(int i=small;i<=big;i++)

System.out.println(i);

small++;

}

else

{

if(curSum>s)

small++;

else

big++;

}

}

posted @ 2015-05-03 10:00  keedor  阅读(114)  评论(0编辑  收藏