From 586b8efd38f2ee919c38b207d7fcb0a442def32c Mon Sep 17 00:00:00 2001 From: Heeqw <124508798+Heeqw@users.noreply.github.com> Date: Mon, 29 Jan 2024 23:39:32 +0800 Subject: [PATCH] =?UTF-8?q?Update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加java语言版本的双指针法 --- problems/0001.两数之和.md | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 1785fe5f..80218cb5 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -133,6 +133,7 @@ public: ### Java: ```java +//使用哈希表 public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; if(nums == null || nums.length == 0){ @@ -151,6 +152,43 @@ public int[] twoSum(int[] nums, int target) { return res; } ``` +```java +//使用双指针 +public int[] twoSum(int[] nums, int target) { + int m=0,n=0,k,board=0; + int[] res=new int[2]; + int[] tmp1=new int[nums.length]; + //备份原本下标的nums数组 + System.arraycopy(nums,0,tmp1,0,nums.length); + //将nums排序 + Arrays.sort(nums); + //双指针 + for(int i=0,j=nums.length-1;itarget) + j--; + else if(nums[i]+nums[j]==target){ + m=i; + n=j; + break; + } + } + //找到nums[m]在tmp1数组中的下标 + for(k=0;k