• 求绝对值最小的数


    题目

    有一个升序排列的数组,数组中可能有正数,负数或0. 求数组中元素的绝对值最小的数.
    例如 数组{-10, 05, 02 ,7,15,50} 绝对值最小的是-2

    解答

    #include <bits/stdc++.h>
    using namespace std;
    
    void f(int a[], int len) {
        if (a[len-1] <= 0) {
            cout << abs(a[len-1]) <<endl;
            return ;
        }
        if (a[0] >= 0) {
            cout << a[0] << endl;
            return ;
        }
        // 有正有负
        int l = 0, r = len-1;
        while (l <= r) {
            int m = (l + r) / 2;
            if(a[m] == 0) {
                cout << a[m] << endl;
                return ;
            } else if(a[m] > 0) {
                if(a[m-1] < 0) {
                    int mn = min(abs(a[m-1]), a[m]);
                    cout<< mn <<endl;
                    return ;
                } else if (a[m-1] == 0) {
                    cout << 0 <<endl;
                    return ;
                } else {
                    // a[m-1] > 0
                    r = m-1;
                }
            } else {
                // a[m] < 0
                if(a[m+1] > 0) {
                    int mn = min(abs(a[m]), a[m+1]);
                    cout << mn <<endl;
                    return ;
                } else if(a[m+1] == 0) {
                    cout << 0 <<endl;
                    return ;
                } else {
                    // a[m+1] < 0
                     l = m+1;
                }
            }
    
        }
        return ;
    }
    
    int main()
    {
        int a1[] = {-10, -5, -2, 7, 15 ,50};
        int a2[] = {2,4,6,8,27};
        int a3[] = {-13, -9, -7, -3};
        int l1 = 6, l2 = 5, l3 = 4;
        f(a1, l1);
        f(a2, l2);
        f(a3, l3);
        return 0;
    }
    
  • 相关阅读:
    187A Permutations
    DFS 专题 哈密顿绕行世界问题
    DFS 专题 N皇后
    DFS专题 Prime Ring Problem
    USACO section1.1 Broken Necklace
    USACO section1.2 Dual Palindromes
    PHPUnitWriting Tests for PHPUnit
    PHP 定界符 使用技巧
    concat函数
    mysql_free_result
  • 原文地址:https://www.cnblogs.com/Draymonder/p/10703605.html
Copyright © 2020-2023  润新知