In this blog, I gave the solution of Equilibrium Index Problem (O(N)) in Three Languages.
The first one is writen in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class Solution { public int solution(int[] arr){
int sumright=0; int sumleft=0; int index=0; for(int i=0;i<arr.length;i++){ sumright+=arr[i]; }
for(int i=0;i<arr.length;i++){ sumleft+=arr[i]; sumright-=arr[i]; if(sumleft==sumright){ return i; }else if(sumleft>sumright){ return -1; } } return -1; } }
int[] arr={5,7,1,3,4,3,7,2}; System.out.print(new Solution().solution(arr));
|
The second one is writen in python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution: def slotion(self,arr): sumleft = 0 sumright = 0 for item in arr: sumright = sumright + item
for item in arr: sumleft = sumleft + item sumright = sumright - item if sumleft == sumright: return arr.index(item) elif sumleft > sumright: return -1
|
The third one is writen in c#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| namespace algorithm { public class Solution { public int solution(int[] arr) { int sumright = 0; int sumleft = 0; for (int i = 0; i < arr.Count(); i++) { sumright += arr[i]; }
for (int i = 0; i < arr.Count(); i++) { sumleft += arr[i]; sumright -= arr[i]; if (sumleft == sumright) { return i; } else if (sumleft > sumright) { return -1; } } return -1; } } }
int[] arr={5,7,1,3,4,3,7,2}; Console.WriteLine(new Solution().solution(arr)); Console.Read();
|