File tree 4 files changed +17
-20
lines changed
solution/0000-0099/0001.Two Sum
4 files changed +17
-20
lines changed Original file line number Diff line number Diff line change 7
7
"bracketSpacing": true,
8
8
"arrowParens": "avoid",
9
9
"phpVersion": "8.1",
10
- "braceStyle": "1tbs"
10
+ "braceStyle": "1tbs",
11
+ "endOfLine": "lf"
11
12
}
Original file line number Diff line number Diff line change @@ -244,13 +244,12 @@ class Solution {
244
244
* @return Integer[]
245
245
*/
246
246
function twoSum($nums, $target) {
247
- $len = count($nums);
248
- for ($i = 0; $i < $len; $i++) {
249
- for ($j = 1 + $i; $j < $len; $j++) {
250
- if ($nums[$i] + $nums[$j] == $target) {
251
- return [$i, $j];
252
- }
247
+ foreach ($nums as $key => $x) {
248
+ $y = $target - $x;
249
+ if (isset($hashtable[$y])) {
250
+ return [$hashtable[$y], $key];
253
251
}
252
+ $hashtable[$x] = $key;
254
253
}
255
254
}
256
255
}
Original file line number Diff line number Diff line change @@ -233,13 +233,12 @@ class Solution {
233
233
* @return Integer[]
234
234
*/
235
235
function twoSum($nums, $target) {
236
- $len = count($nums);
237
- for ($i = 0; $i < $len; $i++) {
238
- for ($j = 1 + $i; $j < $len; $j++) {
239
- if ($nums[$i] + $nums[$j] == $target) {
240
- return [$i, $j];
241
- }
236
+ foreach ($nums as $key => $x) {
237
+ $y = $target - $x;
238
+ if (isset($hashtable[$y])) {
239
+ return [$hashtable[$y], $key];
242
240
}
241
+ $hashtable[$x] = $key;
243
242
}
244
243
}
245
244
}
Original file line number Diff line number Diff line change 1
1
class Solution {
2
-
3
2
/**
4
3
* @param Integer[] $nums
5
4
* @param Integer $target
6
5
* @return Integer[]
7
6
*/
8
7
function twoSum($nums, $target) {
9
- $len = count ($nums );
10
- for ($i = 0 ; $i < $len ; $i ++ ) {
11
- for ($j = 1 + $i ; $j < $len ; $j ++ ) {
12
- if ($nums [$i ] + $nums [$j ] == $target ) {
13
- return [$i , $j ];
14
- }
8
+ foreach ($nums as $key => $x) {
9
+ $y = $target - $x;
10
+ if (isset($hashtable[$y])) {
11
+ return [$hashtable[$y], $key];
15
12
}
13
+ $hashtable[$x] = $key;
16
14
}
17
15
}
18
16
}
You can’t perform that action at this time.
0 commit comments