[Toggle Comments]
package main // file: impl-001.go // Brute force. // // Loop through each element to match the target. // // time: O(n^2); space: O(1). func twoSumBruteForce(nums []int, target int) []int { for i, n := range nums { for j, m := range nums[(i + 1):] { if n+m != target { // Not found. Check the next pairing. continue } // for nums [1,2,3,4,5] the (n,m) pair at each iteration will be as // follows: // // j:0 j:1 j:2 j:3 // i:0 -> … (1,2) (1,3) (1,4) (1,5) // // j:0 j:1 j:2 // i:1 -> … … (2,3) (2,4) (2,5) // // j:0 j:1 // i:2 -> … … … (3,4) (3,5) // // j:0 // i:3 -> … … … … (4,5) // // Observe that—unlike a regular for loop—`j` does not start from // `i+1`, instead, it starts from `0`. // Thus, we’ll need to offset it by `(i + 1)` to get the // corresponding index in the `nums` slice. jShifted := j + (i + 1) // Found a match. return []int{i, jShifted} } } // No match found. return []int{-1, -1} } /* * \ * \\, * \\\,^,.,,. Zero to Hero * ,;7~((\))`;;,, <zerotohero.dev> * ,(@') ;)`))\;;', stay up to date, be curious: learn * ) . ),(( ))\;, * /;`,,/7),)) )) )\,, * (& )` (,((,((;( ))\, */