轩辕互动面试1题

下午去轩辕互动面试了,可是第一轮就被刷了。没办法,没有那本事。
面试时问的是上一次做的一个题目:查找一个排好序的数组中绝对值不相同的数的个数。
我以前做的一个算法的复杂度为nlog(n), 晚上回来好好想了想,终于想出了一个O(n)的算法

public class DistinctCount{
	public static int distinctCount(int[] data){
		int start = 0;
		int end = data.length - 1;
		int count = 0;
		
		while(start <= end){
			while((start < (data.length - 1)) && (data[start] == data[start + 1]) && (start <= end)){
				start++;
				count++;
			}
			
			
			while((end > 0) && (data[end] == data[end - 1]) && (start <= end)){
				end--;
				count++;
			}
			
			if(start > end)
				break;
				
			if((data[start] == data[end]) || (data[start] + data[end] == 0)){
				start++;
				end--;
				count++;
			}else if(data[start] >= 0 || data[end] <= 0){
				start++;
			}else{
				if(data[start] + data[end] < 0)
					start++;
				else
					end--;
			}
		}
		
		return data.length - count + 1;
	}
	
	public static void main(String[] args){
		//int data[] = {-10, -10, -9, -9, -8, -7, -5, -3, 0, 1, 2, 2, 3, 3, 4, 5, 5, 5, 6, 7, 7};
		int data[] = {1, 1, 1, 1, 1};
		System.out.println(DistinctCount.distinctCount(data));
	}
}

你可能感兴趣的:(算法,面试,J#)