求两个排序数组的并集

问题: 

给你两个排序的数组,求两个数组的并集。比如: A = 1 3 4 5 7, B = 2 3 5 8 9, 那么并集就是 1 2 3 4 5 7 8 9.

代码:

public class Union {

	public static void main(String[] args) {
		char[] ch1 = "abcde".toCharArray();
		char[] ch2 = "cekpq".toCharArray();
		
		LinkedList<Character> list = union(ch1, ch2);
		
		for (Character c : list) {
			System.out.println(c);
		}
		
	}
	
	static LinkedList<Character> union(char[] a1, char[] a2) {
		
		if (a1 == null || a2 == null) return null;
		int i = 0;
		int j = 0;
		//save the union 
		LinkedList<Character> list = new LinkedList<Character>();
		
		while(i < a1.length && j < a2.length ) {
			if (a1[i] < a2[j] ) {
				list.add(a1[i]);
				i++;
				while (i < a1.length && a1[i - 1] == a1[i]) {
					i++;
				}
			} else if (a1[i] > a2[j]) {
				list.add(a2[j]);
				j++;
				while (j < a2.length && a2[j - 1] == a2[j]) {
					j++;
				}
			} else {
				list.add(a1[i]);
				i++;
				while (i < a1.length && a1[i - 1] == a1[i]) {
					i++;
				}
				
				j++;
				while (j < a2.length && a2[j - 1] == a2[j]) {
					j++;
				}
			}
		}
			
		while (i < a1.length) {
			list.add(a1[i]);
			i++;
			while (i < a1.length && a1[i - 1] == a1[i]) {
				i++;
			}
		}
		
		while (j < a2.length) {
			list.add(a2[j]);
			j++;
			while (j < a2.length && a2[j - 1] == a2[j]) {
				j++;
			}
		}
		
		return list;
	}
}
转载请注明出处:http://blog.csdn.net/beiyetengqing

你可能感兴趣的:(c,list,String,null,Class,character)