面试题41:和为s的两个数VS和为s的连续正数数列

问题说明:

1.和为s的两个数问题是从一个排序的数组中找出和为s的两个数;

2.原题是找出一个即可,现在全部找出;

3.和为s的连续正数数列是给定一个数找出所有连续正数数列的和为s,例如s为9,(2,3,4)就是其中一组。

(一)和为s的两个数问题

public static int findNumbersWithSum(int[] sorted, int fromIndex, int toIndex, int sum){
	if(null == sorted || sorted.length == 0){
		throw new IllegalArgumentException();
	}
	// allow one element in sorted but at least two elment to make a pair
	if(fromIndex > toIndex){
		throw new IndexOutOfBoundsException("fromIndex : " + fromIndex + "toIndex : " + toIndex);
	}
	
	int countPair = 0;// return value 
	int smallIndex = fromIndex;
	int bigIndex = toIndex;
	int currentSum = 0;
	while(smallIndex < bigIndex){
		
		currentSum = sorted[smallIndex] + sorted[bigIndex];
		
		if(currentSum > sum){
			bigIndex--;
		}
		
		if(currentSum < sum){
			smallIndex++;
		}
		
		if(currentSum == sum){
			int firstNotEqualSmall = smallIndex + 1;
			while(firstNotEqualSmall < bigIndex && (sorted[firstNotEqualSmall] == sorted[smallIndex])){
				firstNotEqualSmall++;
			}
			int firstNotEqualBig = bigIndex - 1;
			while(firstNotEqualBig > smallIndex && (sorted[firstNotEqualBig] == sorted[bigIndex])){
				firstNotEqualBig--;
			}
			//int equalSmallLen = firstNotEqualSmall - smallIndex;
			//int equalBigLen = bigIndex - firstNotEqualBig;
			// may be i == j so add condition by i < j
			for(int i = smallIndex; i < firstNotEqualSmall; i++){
				for(int j = bigIndex; (i < j) && (j > firstNotEqualBig); j--){
					countPair++;
					System.out.println("equal sum = " + sum + " pair index is (" + i + "," + j + ")" 
				                        + " and value is (" + sorted[i] + "," + sorted[j] + ")");
				}
			}
			// go on to find again
			smallIndex = firstNotEqualSmall;
			bigIndex = firstNotEqualBig;
		}// end if ==
		
	}//end while
	return countPair;
}
(二)和为s的连续正数数列

public static void findContinousSequence(int sum){
	if(sum < 3){
		return ;
	}
	int small = 1;
	int big = 2;
	int currentSum = 3;
	int middle = (1 + sum) >> 1;
	while(small < middle){
		if(currentSum == sum){
			print(small, big);
		}
		while(currentSum > sum && small < middle){
			currentSum -= small;
			small++;
			if(currentSum == sum){
				print(small, big);
			}
		}
		// maybe currentSum < sum or small >= middle
		big++;
		currentSum += big;
		
				
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值