第二次尝试结果:成功
第二次过程如下
#include <stdio.h>
void Bub_Sort(int* head, int low, int high, int Bool) {
//多次交换
int temp; //交换
int temp1; //优化
for(int i = low; i < high; i++) {
temp1 = high-(i-low);
for(int j = low+1; j <= temp1; j++) {
//使得head[j]始终为最值
//Bool等于1为递增序列,Bool不等于1为递减序列
if((head[j] < head[j-1]) == Bool) {
temp = head[j];
head[j] = head[j-1];
head[j-1] = temp;
}
}
}
}
int Seekaim(int* nums, int aim, int left, int right) {
//在[l,r]搜寻aim的位置,-1:不存在
if(nums[left] <= aim && aim <= nums[right]) {
while(left < right) {
if(nums[(left+right)/2] < aim) {
left = (left+right)/2+1;
}else {
right = (left+right)/2;
}
}
}
return nums[left] == aim?left: -1;
}
void threeSum(int* nums, int numsSize) {
Bub_Sort(nums, 0, numsSize-1, 1); //进行顺序排序
int last = 0; //搜索下界
int base_seek;//搜寻子基址
int seek; //搜寻子
int last_negative_seek =last+2; //上一个负搜寻子
int last_positive_seek = numsSize-1; //上一个正搜寻子
int flag; //1:搜寻子seek为目标值,0:搜寻子seek不为目标值
int temp;
while(nums[last]<=0 && (numsSize-1)-last>=2){
base_seek=last+1;
flag=0;
while(!flag && base_seek<=numsSize-2){
temp=nums[last]+nums[base_seek];
if(temp>=0){//目标值为非正数,在[last+2,最后一个非正数]进行搜索
seek=last_negative_seek;
if(nums[seek]+temp>=0){//在[last+2,last_negative_seek]进行搜索
for(seek;seek>last+1;seek--){
//if(nums[seek]>0) break;
if(nums[seek]+temp==0){
flag=1;
break;
}
}
}
else{//在[last_negative_seek+1,最后一个非正数]进行搜索
seek++;
while(seek<numsSize-1 && nums[seek]<=0){
if(nums[seek]+temp==0){
flag=1;
break;
}
seek++;
}
}
if(flag){
last_negative_seek=seek;
printf("%d %d %d\n",nums[last],nums[base_seek],nums[seek]);
}
else{
if(last_negative_seek-last<2){
last_negative_seek=last+2;
}
}
}
else{//目标值为正数,在[第一个正数,numsSize-1]进行搜索
seek=last_positive_seek;
if(nums[seek]+temp>=0){//在[第一个正数,last_positive_seek]进行搜索
while(seek>last+1 && nums[seek]>0){
if(nums[seek]+temp==0){
flag=1;
break;
}
seek--;
}
}
else{//在[last_positive_seek+1,numsSize-1]进行搜索
seek++;
for(seek;seek<numsSize;seek++){
//if(nums[seek]j<=0) break;
if(nums[seek]+temp==0){
flag=1;
break;
}
seek++;
}
}
if(flag){
last_positive_seek=seek;
printf("%d %d %d\n",nums[last],nums[base_seek],nums[seek]);
}
}
base_seek++;
}
last++;
}
}
int main() {
int nums[15] = {
7,7,7, 5, 3, 0, 0, 0, -1, 4, -6, -7, 2, -4, 2
};
threeSum(nums, sizeof(nums)/sizeof(nums[0]));
return 0;
}