@@ -11,30 +11,50 @@ void main() {
1111}
1212
1313class Solution {
14- ////! Binary Search
15- ////! The more hard solution with Binary Search TC: O(n*log(n) )
14+ ////! AI Solution Two Pointers (The Fastest) TC: O(n)
15+ ////! The more hard solution with Binary Search TC: O(n)
1616 ////! Accepted And Faster
1717 List <int > twoSum (List <int > numbers, int target) {
18- for (int i = 0 ; i < numbers.length - 1 ; i++ ) {
19- final int otherNumber = target - numbers[i];
20- int leftIndex = i + 1 ;
21- int rightIndex = numbers.length - 1 ;
22-
23- while (leftIndex <= rightIndex) {
24- int mid = leftIndex + (rightIndex - leftIndex) ~ / 2 ;
25- if (numbers[mid] == otherNumber) {
26- return [i + 1 , mid + 1 ];
27- } else if (numbers[mid] > otherNumber) {
28- rightIndex = mid - 1 ;
29- } else {
30- leftIndex = mid + 1 ;
31- }
18+ int leftIndex = 0 ;
19+ int rightIndex = numbers.length - 1 ;
20+ while (leftIndex <= rightIndex) {
21+ int sum = numbers[leftIndex] + numbers[rightIndex];
22+ if (sum == target) {
23+ return [leftIndex + 1 , rightIndex + 1 ];
24+ } else if (sum > target) {
25+ rightIndex-- ;
26+ } else {
27+ leftIndex++ ;
3228 }
3329 }
3430
3531 return [];
3632 }
3733
34+ ////! Binary Search : TC: O(n*log(n))
35+ ////! The more hard solution with Binary Search TC: O(n*log(n))
36+ ////! Accepted And Faster
37+ // List<int> twoSum(List<int> numbers, int target) {
38+ // for (int i = 0; i < numbers.length - 1; i++) {
39+ // final int otherNumber = target - numbers[i];
40+ // int leftIndex = i + 1;
41+ // int rightIndex = numbers.length - 1;
42+
43+ // while (leftIndex <= rightIndex) {
44+ // int mid = leftIndex + (rightIndex - leftIndex) ~/ 2;
45+ // if (numbers[mid] == otherNumber) {
46+ // return [i + 1, mid + 1];
47+ // } else if (numbers[mid] > otherNumber) {
48+ // rightIndex = mid - 1;
49+ // } else {
50+ // leftIndex = mid + 1;
51+ // }
52+ // }
53+ // }
54+
55+ // return [];
56+ // }
57+
3858 ////! Burte Force
3959 ////! The easy solution --> TC: O(n^2)
4060 ////! Accepted But Slow
0 commit comments