Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 586b8ef

Browse files
authored
Update 0001.两数之和.md
增加java语言版本的双指针法
1 parent abc86e9 commit 586b8ef

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎problems/0001.两数之和.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ public:
133133
### Java:
134134
135135
```java
136+
//使用哈希表
136137
public int[] twoSum(int[] nums, int target) {
137138
int[] res = new int[2];
138139
if(nums == null || nums.length == 0){
@@ -151,6 +152,43 @@ public int[] twoSum(int[] nums, int target) {
151152
return res;
152153
}
153154
```
155+
```java
156+
//使用双指针
157+
public int[] twoSum(int[] nums, int target) {
158+
int m=0,n=0,k,board=0;
159+
int[] res=new int[2];
160+
int[] tmp1=new int[nums.length];
161+
//备份原本下标的nums数组
162+
System.arraycopy(nums,0,tmp1,0,nums.length);
163+
//将nums排序
164+
Arrays.sort(nums);
165+
//双指针
166+
for(int i=0,j=nums.length-1;i<j;){
167+
if(nums[i]+nums[j]<target)
168+
i++;
169+
else if(nums[i]+nums[j]>target)
170+
j--;
171+
else if(nums[i]+nums[j]==target){
172+
m=i;
173+
n=j;
174+
break;
175+
}
176+
}
177+
//找到nums[m]在tmp1数组中的下标
178+
for(k=0;k<nums.length;k++){
179+
if(tmp1[k]==nums[m]){
180+
res[0]=k;
181+
break;
182+
}
183+
}
184+
//找到nums[n]在tmp1数组中的下标
185+
for(int i=0;i<nums.length;i++){
186+
if(tmp1[i]==nums[n]&&i!=k)
187+
res[1]=i;
188+
}
189+
return res;
190+
}
191+
```
154192

155193
### Python:
156194
(版本一) 使用字典

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /