G
N
I
D
A
O
L

15. 三数之和

三指针

15. 三数之和

C++

vector<vector<int>> threeSum(vector<int>& nums) 
{
	vector<vector<int>> ans;
	int n = nums.size();
	sort(nums.begin(), nums.end());
	for (int first = 0; first < n; first++)
	{
		if (first > 0 && nums[first] == nums[first - 1])
			continue;
		int third = n - 1;
		int target = -nums[first];
		for (int second = first + 1; second < n; ++second)
		{
			if (second > first + 1 && nums[second] == nums[second - 1])
				continue;
			while (second < third && nums[second] + nums[third] > target) {
				--third;
			}
			if (third == second)
				break;
			if (nums[second] + nums[third] == target)
			{
				ans.push_back({ nums[first],nums[second],nums[third] });

			}

		}


	}
	return ans;
}

C

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int compInt(const void *a, const void *b)
{
	return *(int*)a - *(int*)b;
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
    	*returnSize = 0;
	// 首先判断数组大小
	if(nums == NULL || numsSize < 3)
	{
		return NULL;
	}
	
	// 对数组排序
	qsort(nums,numsSize, sizeof(int),compInt);

	// 为return申请空间
	int **ans = (int**)malloc(sizeof(int*) * (numsSize) * (numsSize));
	*returnColumnSizes = (int*)malloc(sizeof(int) * (numsSize) * (numsSize));


	// 三指针遍历
	int cur = 0;
	int low = cur + 1;
	int high = numsSize - 1;

	 // 第一层 头指针
	while (nums[cur] <= 0 && (cur + 1) < (numsSize - 1) )
	{
		low = cur + 1;
		high = numsSize - 1;
		
		// 第二层 双指针求 sum == 0
		while (low < high)
		{
			int sum = nums[low] + nums[cur] + nums[high]; 
			if( 0 == sum )
			{
				ans[*returnSize] = (int*)malloc(sizeof(int)*3);
				ans[*returnSize][0] = nums[cur];
				ans[*returnSize][1] = nums[low];
				ans[*returnSize][2] = nums[high];
				
				(*returnColumnSizes)[*returnSize] = 3;
				(*returnSize)++;

				// 去重
				while( (nums[low] == nums[++low]) && (low < high));
				while( (nums[high] == nums[--high]) && (low < high));
			}
			else if (0 < sum)
			{
				high--;
			}
			else
			{
				low++;
			}

		}

		while (nums[cur] == nums[++cur] && (cur + 1 < numsSize - 1) );
	}

	return ans;
}
posted @ 2021-07-19 14:35  StimuMing  阅读(41)  评论(0编辑  收藏  举报