Day4
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_977._Squares_of_a_Sorted_Array</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
11
977. Squares of a Sorted Array/Program.cs
Normal file
11
977. Squares of a Sorted Array/Program.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace _977._Squares_of_a_Sorted_Array
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
var res = new Solution().SortedSquares(new int[] { -7, -2,-1 });
|
||||
Console.WriteLine(String.Join(" ", res));
|
||||
}
|
||||
}
|
||||
}
|
||||
49
977. Squares of a Sorted Array/Solution.cs
Normal file
49
977. Squares of a Sorted Array/Solution.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
namespace _977._Squares_of_a_Sorted_Array;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public int[] SortedSquares(int[] nums)
|
||||
{
|
||||
int[] res = new int[nums.Length];
|
||||
int firstNonNegative = -1;
|
||||
for(int i = 0; i < nums.Length; i++)
|
||||
{
|
||||
if (nums[i] >= 0)
|
||||
{
|
||||
firstNonNegative = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int resIndex = 0;
|
||||
int positiveIndex = firstNonNegative;
|
||||
int negativeIndex = firstNonNegative!=-1 ? positiveIndex - 1 : nums.Length-1;
|
||||
while(resIndex < nums.Length)
|
||||
{
|
||||
if(negativeIndex>=0 && positiveIndex < nums.Length && positiveIndex>=0)
|
||||
{
|
||||
if (nums[negativeIndex]*-1 < nums[positiveIndex])
|
||||
{
|
||||
res[resIndex++] = nums[negativeIndex] * nums[negativeIndex];
|
||||
negativeIndex--;
|
||||
}
|
||||
else
|
||||
{
|
||||
res[resIndex++] = nums[positiveIndex] * nums[positiveIndex];
|
||||
positiveIndex++;
|
||||
}
|
||||
}
|
||||
else if(negativeIndex >= 0)
|
||||
{
|
||||
res[resIndex++] = nums[negativeIndex]* nums[negativeIndex];
|
||||
negativeIndex--;
|
||||
}
|
||||
else if(positiveIndex >= 0)
|
||||
{
|
||||
res[resIndex++] = nums[positiveIndex] * nums[positiveIndex];
|
||||
positiveIndex++;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user