3sum-closest.dart (795B)
1 //Find the three values in a list that add up to the number 2 //closest to the target. Once found return that number. 3 //This is the brute force solution which is very slow. 4 //Time: 3180ms Beats: 8.33% 5 //Memory: 158.3MB Beats: 8.33% 6 7 class Solution { 8 int threeSumClosest(List<int> nums, int target) { 9 int closest = (nums[0] + nums[1] + nums[2] - target).abs(); 10 int val = nums[0] + nums[1] + nums[2]; 11 for(int i = 1 ; i < nums.length ; ++i){ 12 for(int x = i + 1; x < nums.length ; ++x){ 13 for(int z = x + 1; z < nums.length ; ++z){ 14 if((nums[i] + nums[x] + nums[z] - target).abs() < closest){ 15 closest = (nums[i] + nums[x] + nums[z] - target).abs(); 16 val = nums[i] + nums[x] + nums[z]; 17 } 18 } 19 } 20 } 21 return val; 22 } 23 }