双指针(基础算法题)

1.合并两个有序数组

给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。思路:利用system.arraycopy(nums1, int srcPos, nums2, int destPos, int length)将数组合并后将数组进行排序(用Arrays.sort排序)

参数说明:

nums1:源数组
srcPos:源数组要复制的起始位置
nums2:目的数组
destPos:目的数组放置的起始位置
length:复制的长度

public class T5 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new 	Scanner(System.in);
		System.out.println("请输入n的值:");
		int n=sc.nextInt();
		System.out.println("请输入m的值:");
		int m=sc.nextInt();
		int[] num1=new int[n+m];
		int[] num2=new int[m];
		for(int i=0;i<(m+n);i++) {
			System.out.println("请输入数组1第"+(i+1)+"个数的值");
			int a=sc.nextInt();
			num1[i]=a;
		}
		for(int i=0;i<m;i++) {
			System.out.println("请输入数组2第"+(i+1)+"个数的值");
			int a=sc.nextInt();
			num1[i]=a;
		}
		
		hebing(num1,m,num2,n);
	}
	public static void hebing(int num1[],int m,int num2[],int n) {
		System.arraycopy(num2,0, num1,n,m);
		Arrays.sort(num1);
		System.out.println(num1);
	}
}

2.三数之和

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

思路:首先判断数组的长度是否大于3,小于3时返回一个空的数组,当数组长度大于3,对数组进行排序后往下进行。如果三数和等于0,将三个数的值添加到数组中去。判断左界和右界是否和下一位置重复,若重复则往下一个位置移动。
若和大于 0,说明 nums[R] 太大,R 左移
若和小于 0,说明 nums[L] 太小,L 右移

public class 三数和 {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int[] nums=new int[n];
		for(int i=0;i<n;i++) {
			System.out.println("请输入你要输入的数组值");
			int a=sc.nextInt();
			nums[i]=a;
		}
		System.out.println(threeSum(nums));

	}

	public static List<List<Integer>> threeSum(int[] nums) {
		int n = nums.length;
		List<List<Integer>> res = new ArrayList<>();
		if (nums.length < 3) {
			return res;
		}

		Arrays.sort(nums);
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] > 0) {
				return res;
			} else if (i > 0 && nums[i] == nums[i - 1]) {
				continue;
			}
			int L = i + 1;
			int R = n - 1;
			while (L < R) {
				if (nums[i] + nums[L] + nums[R] == 0) {
					res.add(Arrays.asList(nums[i], nums[L], nums[R]));
					while (L < R && nums[L] == nums[L + 1]) {
						L = L + 1;
					}
					while (L < R && nums[R] == nums[R - 1]) {
						R = R - 1;
					}
					L = L + 1;
					R = R - 1;
				} else if (nums[i] + nums[L] + nums[R] > 0) {
					R = R - 1;
				} else {
					L = L + 1;
				}

			}
		}
		return res;
	}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值