`

在一个集合s中寻找最大的C,使得C = A + B,且ABC均在集合s当中

阅读更多
package com.java.google;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * 在一个集合s中寻找最大的C,使得C = A + B,且ABC均在集合s当中
 * @author yuahan
 *
 */
public class ABC_Set {
	
	public static int[] getRandomArray(int max, int length){
		if(length <= 0){
			length = 20;
		}
		if(max <= 0){
			max = 2000;
		}
		Random random = new Random();
		Set<Integer> set = new HashSet<Integer>();
		for(;;){
			set.add(random.nextInt(max));
			if(set.size() == length){
				break;
			}
		}
		
		Integer[] array = set.toArray(new Integer[length]);
		int[] result = new int[length];
		for(int i=0;i<length;i++){
			result[i] = array[i];
		}
		return result;
	}
	
	public static int[] getC(int[] s){
		Arrays.sort(s);
		int[] result = new int[3];
		for(int i=s.length - 1;i>=0;i--){
			for(int j=0,k=i-1;k>j;){
				if(s[j] + s[k] > s[i]){
					k--;
					continue;
				}else if(s[j] + s[k] < s[i]){
					j++;
					continue;
				}else{
					result[0]= s[i];
					result[1]= s[j];
					result[2]= s[k];
					return result;
				}
			}
		}
		return null;
	}
	
	public static void main(String[] args) {
		int[] s = ABC_Set.getRandomArray(200, 20);
		Arrays.sort(s);
		System.out.println(Arrays.toString(s));
		int result[] = ABC_Set.getC(s);
		System.out.println(Arrays.toString(result));
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics