Created
October 22, 2018 20:52
-
-
Save jianminchen/418e31889b11abfafb8eb336170771da to your computer and use it in GitHub Desktop.
927 three equal parts - first submission
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int[] ThreeEqualParts(int[] digits) | |
{ | |
if (digits == null) | |
return new int[] {-1, - 1}; | |
var countof1 = 0; | |
var length = digits.Length; | |
var map = new Dictionary<int, int>(); | |
for(int i = 0; i < length; i++) | |
{ | |
if (digits[i] == 1) | |
{ | |
map.Add(countof1, i); | |
countof1++; | |
} | |
} | |
if (countof1 % 3 != 0) | |
return new int[] { -1, -1 }; | |
if(countof1 == 0) | |
return new int[]{0, 2}; | |
int number1 = countof1 / 3; | |
// find the number | |
int thirdNumberStart = map[countof1 - number1]; | |
// constraint | |
int numberLength = length - thirdNumberStart; | |
// compare the first number with third number | |
int firstNumberStart = map[0]; | |
int index1 = map[0]; | |
int index2 = map[numberLength]; | |
int index3 = map[countof1 - number1]; // 3, 2 ; 6; | |
if(length - index1 + 1 < 3 * numberLength) | |
return new int[]{-1, -1}; | |
var result = checkFirstAndThird(digits, index1, index3) && checkFirstAndThird(digits, index1, index2); | |
if(!result) | |
return new int[]{-1, -1}; | |
return new int[] { index1 + numberLength - 1, index2 + numberLength }; | |
} | |
private static bool checkFirstAndThird(int[] digits, int index1, int index3) | |
{ | |
var length = digits.Length; | |
for(int i = index3, j = index1; i < length && j < length; i++, j++) | |
{ | |
if (digits[i] != digits[j]) | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment