/*快排后 取最小两个负数和最大正数乘积和最大三个正数乘积比较取较大值*/ int cmp(const void* a, const void* b){ return *(int*)a - *(int*)b; } int maximumProduct(int* nums, int numsSize){ qsort(nums,numsSize,sizeof(int),cmp); int val1,val2; val1 = nums[0]*nums[1]*nums[numsSize-1]; val2 = nums[numsSize-1]*nums[numsSize-2]*nums[numsSize-3]; return (val1>val2)? val1: val2; }
//线性扫描 int maximumProduct(int* nums, int numsSize){ int a = -1000; int b = -1000; int c = -1000; int d = 1000; int e = 1000; for(int i=0 ; i < numsSize ; i++){ if(nums[i] < d){ e = d; d = nums[i]; } else if(nums[i] < e){ e = nums[i]; } if(nums[i] > c){ a = b; b = c; c = nums[i]; } else if(nums[i] > b){ a = b; b = nums[i]; } else if(nums[i] > a){ a = nums[i]; } } int result1 = a*b*c; int result2 = d*e*c; if(result1 > result2){ return result1; } return result2; }