--------------------2019/1/23----------------------
我现在重新写一下这道题:
这道题真的好!
题目链接:https://leetcode-cn.com/problems/maximum-product-of-three-numbers/
public class Solution {
public int MaximumProduct(int[] nums) {
//先排序
Array.Sort(nums);
//记录数组长度
int length = nums.Length;
//该题主要考查数组中包含负数的情况
//如果全为正数,排序后输出后3位的乘积即可
//否则,最大值一定在最小的2个负数和最大数的乘积、后3位值的乘积中产生
//直接比较它们的大小输出即可
//先存下数组后3位值的乘积
int product = nums[length - 1] * nums[length - 2] * nums[length - 3];
//取前2位和最后1位的乘积、后3位值的乘积中的最大值
product = Math.Max(product, nums[length - 1] * nums[1] * nums[0]);
//输出这个最大值
return product;
}
}
答案来源:https://blog.csdn.net/qq_31116753/article/details/82319859#commentBox
我之前没有考虑到负数情况,因为没想过要在LeetCode官网上执行,所以才有以下代码:
--------------------2019/1/23----------------------
这道题我想的是先找到最大的三个数在数组中,但是难度很大,索性借用冒泡排序将三个数值排序一下计算就容易多了。
所有程序都是在Visual Studio软件上运行测试成功后copy过来的-----答案如下:
class Program
{
static void Main(string[] args)
{
int sums = 1;
int[] tes = new int[] { 2, 1, 6, 4, 5 };
int[] strss= Get(tes);
for (int i = strss.Length-1; i > 1; i--)
{
sums *= strss[i];
}
Console.WriteLine(sums);
Console.ReadKey();
}
private static int[] Get(int[] nums)
{
//首先,记录最大的三个数的位置,但是要定义三个变量存储最大值。
//倒不如进行排序,然后计算前三个数值
int [] strinput= Getarr(nums);
return nums;
}
private static int[] Getarr(int[] data)
{
for (int i = 0; i < data.Length - 1; i++)
{
for (int j = 0; j < data.Length - 1 - i; j++)
{
if (data[j] > data[j + 1])
{
data[j] = data[j] + data[j + 1];
data[j + 1] = data[j] - data[j + 1];
data[j] = data[j] - data[j + 1];
}
}
}
return data;
}
}
以上程序大量的篇幅写了关于排序的功能,是时候思考几个问题了:
1、已经有了排序数组的函数:
将上面的程序替换一下:
int[] intArr = new int[] { 2, 1, 6, 4, 5 }; Array.Sort(intArr); //正序
Array.Reverse(intArr);//反序
2、我看了一下程序,没有什么多余的了,兄die.