//找出数组中三个数相加为0,返回存在的组数 //输入指正*A,长度为size,返回*B和长度num int threeSum_0(int *A,int size,int *B,int &num) { vector<int> temp(A, A + size); //使用vector操作数据 sort(temp.begin(),temp.end());//sort //夹逼 auto last = temp.end(); int *p = new int[30];//p为临时数组,大小自己设置 for (auto a = temp.begin(); a <prev(last,2); a++){ auto b = next(a); auto c = prev(last); while (b < c){ if (*a + *b + *c > 0) --c; else if (*a + *b + *c < 0) ++b; else{ *(p++) = *a; *(p++) = *b; *(p++) = *c; num = num + 3; ++b; --c; } } } p = p - num; for (int i = 0; i < num; i++) B[i] = p[i]; delete[] p; return num/3; //符合条件的组数 }
时间: 2024-11-05 06:11:59