leetcode-238-OK

address

// 第一种解法,比较好,因为题目不让用除法,而第二种写之前没看清题目,所以用了除法
int* productExceptSelf(int* nums, int numsSize, int* returnSize){
    returnSize[0] = numsSize;
	int* answer = (int *)malloc(sizeof(int) * numsSize);
	answer[0] = 1;
	for(int i = 1;i <numsSize;i++){
		answer[i] = answer[i-1] * nums[i-1];
	}
	int temp1=nums[numsSize-1],temp2;
	nums[numsSize-1] = 1;
	for(int i = numsSize-2; i>=0; i--){
		temp2 = nums[i];
		nums[i] = nums[i+1] * temp1;
		temp1 = temp2;
	}
	for(int i = 0;i <numsSize;i++){
		answer[i] = answer[i]*nums[i];
	}
	return answer;
}
// 第二种解法,有问题,因为题目不让用除法
int* productExceptSelf(int* nums, int numsSize, int* returnSize){
    returnSize[0] = numsSize;
	int all = 1;
	for(int i = 0;i <numsSize;i++){
		all*= nums[i];
	}
	int* answer = (int *)malloc(sizeof(int) * numsSize);
	for(int i = 0;i <numsSize;i++){
		if(nums[i] != 0 )
			answer[i] = all/nums[i];
		else{
			answer[i] =1;
			for(int j =0; j<numsSize;j++){
				if(j ==i)
					continue;
				answer[i] *= nums[j];
			}
		}
	}
	return answer;
}
上一篇:【leetcode】131. 分割回文串


下一篇:【leetcode】102. 二叉树的层序遍历