Vintion's blog

~夜黑路滑,社会复杂~

最小绝对值

| Comments

求一个递增序列中绝对值最小的数

比如(-3, -1, 2,4,6),返回-1

当然,时间小于O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<stdio.h>
#define ABS(x,y) ((-x)>=(y)?(y):(x))
int GetAbsMin(int *a, int n)
{
    if(a[0]>=0)return a[0];
    if(a[n-1]<=0)return a[n-1];
    int begin = 0;
    int end   = n-1;

    int left = a[0];
    int right = a[n-1];
    int mid;
    while(begin<=end)
    {
        mid = (begin+end)/2;
        if(a[mid]==0)return 0;
        if(a[mid]>0)
        {
            if(a[mid-1]<0)
            {
                left = a[mid-1];
                right = a[mid];
                break;
            }
            else
            {
                end = mid-1;
            }
        }
        else
        {
            if(a[mid+1]>0)
            {
                left=a[mid];
                right=a[mid+1];
                break;
            }
            else
                begin = mid + 1;
        }

    }
    return ABS(left,right);
}

int main()
{
    int n,i;
    int a[100];
    int result;
    while(~scanf("%d",&n))
    {
        for(i=0;i<n;i++)
            scanf("%d",&a[i]);
       result =  GetAbsMin(a,n); 
       printf("%d\n",result);
    }
    return 0;
}

Comments