From 8ff7654633a368b5b735f9b194c4fc379062f86e Mon Sep 17 00:00:00 2001 From: fleyx Date: Tue, 28 Nov 2023 23:48:59 +0800 Subject: [PATCH] add --- 5.leetcode/src/com/fanxb/common/Q26.java | 18 +++++++++++++++++- 5.leetcode/src/com/fanxb/common/Q27.java | 15 ++++++++++++++- 5.leetcode/src/com/fanxb/common/Q88.java | 11 ++++++++--- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/5.leetcode/src/com/fanxb/common/Q26.java b/5.leetcode/src/com/fanxb/common/Q26.java index b1685c9..7b183fe 100644 --- a/5.leetcode/src/com/fanxb/common/Q26.java +++ b/5.leetcode/src/com/fanxb/common/Q26.java @@ -1,5 +1,7 @@ package com.fanxb.common; +import java.util.Arrays; + /** * TODO * @@ -23,7 +25,21 @@ public class Q26 { return count; } + public int newRemoveDuplicates(int[] nums) { + int i = 0, j = 1; + while (j < nums.length) { + if (nums[j] != nums[i]) { + nums[++i] = nums[j]; + } + j++; + } + return i + 1; + } + + public static void main(String[] args) { - System.out.println(new Q26().removeDuplicates(new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4})); + int[] arr = new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; + System.out.println(new Q26().newRemoveDuplicates(arr)); + System.out.println(Arrays.toString(arr)); } } diff --git a/5.leetcode/src/com/fanxb/common/Q27.java b/5.leetcode/src/com/fanxb/common/Q27.java index 8f1c634..efc23cd 100644 --- a/5.leetcode/src/com/fanxb/common/Q27.java +++ b/5.leetcode/src/com/fanxb/common/Q27.java @@ -24,7 +24,20 @@ public class Q27 { return count; } + public int removeElement1(int[] nums, int val) { + int i = 0, j = 0; + while (j < nums.length) { + if (nums[j] != val) { + nums[i++] = nums[j]; + } + j++; + } + return i; + } + public static void main(String[] args) { - System.out.println(new Q27().removeElement(new int[]{0, 1, 2, 2, 3, 0, 4, 2}, 2)); + int[] arr = new int[]{0, 1, 2, 2, 3, 0, 4, 2}; + System.out.println(new Q27().removeElement1(arr, 2)); + System.out.println(Arrays.toString(arr)); } } diff --git a/5.leetcode/src/com/fanxb/common/Q88.java b/5.leetcode/src/com/fanxb/common/Q88.java index 16ce71a..41852ea 100644 --- a/5.leetcode/src/com/fanxb/common/Q88.java +++ b/5.leetcode/src/com/fanxb/common/Q88.java @@ -35,14 +35,19 @@ public class Q88 { int[] nums1Copy = new int[m]; System.arraycopy(nums1, 0, nums1Copy, 0, m); for (int i = 0, j = 0, k = 0; k < m + n; k++) { - + if (j>=n || (i < m && nums1Copy[i] < nums2[j])) { + nums1[k] = nums1Copy[i++]; + } else { + nums1[k] = nums2[j++]; + } } - } public static void main(String[] args) { - int[] nums1 = new int[12]; + int[] nums1 = new int[]{1,2,3}; + int[] nums2 = new int[]{}; + new Q88().merge(nums1,3,nums2,0); System.out.println(Arrays.toString(nums1)); } }