轩辕互动面试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));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值