class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] ans = new int[n+m];
int p1 = 0;
int p2 = 0;
int i = 0;
while(p1 < m || p2 < n){
int cur = 0;
if (p1 == m){
cur = nums2[p2];
p2++;
} else if (p2 == n){
cur = nums1[p1];
p1++;
} else if (nums1[p1] < nums2[p2]){
cur = nums1[p1];
p1++;
} else {
cur = nums2[p2];
p2++;
}
ans[i] = cur;
i++;
}
/*for(int j = 0; j<n+m; j++){
System.out.print(ans[j]+" ");
}*/
for (int j = 0; j < m+n; j++){
nums1[j] = ans[j];
}
}
}
2、移除元素
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int j = nums.length - 1;
while (i <= j){
if(nums[i] == val){
nums[i] = nums[j];
nums[j]=val;
j--;
i--;
}
i++;
}
return j+1;
}
}
3、删除有序数组中的重复项
class Solution {
public int removeDuplicates(int[] nums) {
int fast=1;
int slow=1;
while(fast<nums.length){
if(nums[fast]!=nums[fast-1]){
nums[slow++]=nums[fast];
}
fast++;
}
return slow;
}
}
4、删除有序数组中的重复项Ⅱ
class Solution {
public int removeDuplicates(int[] nums) {
int fast=1;
int slow=1;
int cnt=1;
while(fast<nums.length){
if(nums[fast]!=nums[fast-1]){
nums[slow++]=nums[fast];
cnt=1;
}else if(nums[fast]==nums[fast-1]){
cnt++;
if(cnt==2){
nums[slow++]=nums[fast];
}
//System.out.print(cnt);
}
fast++;
}
return slow;
}
}
5、多数元素
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int n=nums.length;
return nums[n/2];
}
}