[问答题]

# 8个回答

```int i = 0;
while( a[i] < 0){
i++;
}
if(a[i] + a[i-1] <= 0)
return a[i];
else
return a[i-1]; ```

int _tmain(int argc, _TCHAR* argv[])
{
vector<int> p;
int num;
while(cin>>num)
p.push_back(num);
int result=0;
int start=0,end=p.size()-1,tempidx;
while(start<end)
{
tempidx=(start+end)/2;
if(tempidx==start)
{
if(abs(p[tempidx])<p[tempidx+1])
result=tempidx;
else
result=tempidx+1;
break;
}
if(p[tempidx]<0)
start=tempidx;
else if(p[tempidx]>0)
end=tempidx;
else
{
result=tempidx;
break;
}
}
cout<<p[result]<<" "<<result<<endl;
return 0;
`}`

```int getMin(vector<int> a, int n)
{
assert(n > 0);
if (a[0] >= 0) return a[0];
if (a[n-1] <= 0) return (-1) * a[n-1];
int l = 0;
int r = n-1;
int res = min((-1)*a[0], a[n-1]);
while (l < r)
{
int m = (l + r) >> 1;
if (a[m] > 0)
{
res = min(res, a[m]);
r = m-1;
}
else if (a[m] < 0)
{
res = min(res, (-1)*a[m]);
l = m+1;
}
else
return a[m];
}
return abs(a[l]);
}

o(logN)时间复杂度```

int g_errno=0;
int absmin(int *nums,int n)
{
if(nums==NULL||n<=0)
{
g_errno=-1;
return 0;
}
int first=0;
int end=n-1;
if(nums[first]>=0)
return nums[first];
if(nums[end]<=0)
return -nums[end];
while(first<end)
{
if(end-first==1)
break;
int mid=end-((end-first)>>1);
if(nums[mid]<0)
first=mid;
else
end=mid;
}
return -nums[first]<nums[end]?-nums[first]:nums[end];
}

```#include <stdio.h>
#include <vector>
using namespace std;

static int GetMin(const vector<int> &data, int begin, int end){
//循环到只剩下两个相邻数字，或者整个序列都是相同符号
if(end - begin == 1 || data[begin] * data[end] >= 0){
return abs(data[end]) > abs(data[begin]) ? data[begin] : data[end];
}

int k = (begin + end) / 2;
//对异号的序列查找
if(data[begin] * data[k] > 0){
return GetMin(data, k, end);
}
return GetMin(data, begin, k);
}

int FindAbsMin(const vector<int> &data){
int m = GetMin(data, 0, data.size() - 1);
printf("%d", m);
return m;
}
int main(){
vector<int> data;
int Num[] = {-4,-3,-2,-1};
for(int i = 0; i < sizeof(Num) / sizeof(Num[0]); ++i){
data.push_back(Num[i]);
}
FindAbsMin(data);
return 0;

}
```

//一组有叙数（从小到大排列），有负有正，找出绝对值最小值。(C或C++)
```int findMinNum(int  nums[], int ilen)
{
int iFirst = 0;
int iSecond = 0;
int iIndex = 0;
for (; iIndex < ilen; iIndex++)
{
iFirst = nums[iIndex];
iSecond = nums[iIndex + 1];
if (iFirst < 0 && iSecond >= 0)
{
break;
}
}
return (-iFirst > iSecond) ? iSecond : -iFirst;

}

int main ()
{
int sss[] = { -4 - 3, -2, -1,  1, 2, 3, 6, 9 };
int ss = findMinNum(sss,sizeof(sss)/sizeof(int));

return 0;
}

```

8条回答 5690浏览

# 相关试题

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题

QQ群：169195721