elimination-game.dart (868B)
1 //Starting from the first index remove every other element. Then 2 //sweep back the other way from right to left until there is only 3 //one value remaining. Return the remaining value. 4 //The time complexity of this code is O(n^2) where n is the length of the list 5 //it is this slow because the a memcopy is required to remove a specific index from a list (O(n) time) 6 //This code is too slow for leet code, but it is the intuitive solution to the problem. 7 // 8 class Solution { 9 int lastRemaining(int n) { 10 List<int> vals = []; 11 for(int i = 1 ; i <= n ; ++i){ 12 vals.add(i); 13 } 14 while(vals.length > 1){ 15 for(int i = 0 ; i < vals.length ; i += 1){ 16 vals.removeAt(i); 17 } 18 if(vals.length == 1){ 19 break; 20 } 21 for(int i = vals.length - 1 ; i >= 0; i -= 2){ 22 vals.removeAt(i); 23 } 24 } 25 return vals[0]; 26 } 27 }