演算法初始記錄
阿新 • • 發佈:2018-12-17
Remove Element
Given an array and a value, remove all instances of that > value in place and return the new length.The order of elements can be changed. It doesn't matter what you leave beyond the new length.
題意:在一個數組裡面移除指定value,並且返回新的陣列長度。
//import java.util.Scanner; class Solution { public static void main(String[] args){ int[] num = {1,2,2,3,4,5}; int y=Removement(num,num.length,2); System.out.println(y); } public static int Removement(int A[], int m, int elem) { int i = 0; int j = 0; for (i = 0; i < m; i++) { if (A[i] == elem) { continue; } A[j] = A[i]; j++; } return j; } }
第一次的程式碼寫出來,執行不出來,老是輸出異常,對於函式引數對於陣列的呼叫還有有點沒有搞懂,還是等過一段時間我在看吧
下一題
下一題
Remove Duplicates from Sorted Array
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 緊接著上一題,同樣是移除重複的元素,但是可以允許最多兩次重複元素存在。
public class Solution2 {
public static void main(String[] args){
int a[]={1,1,1,2,2,3,0,3};
int x=removeDuplicates(a,a.length);
System.out.println(x);
}
public static int removeDuplicates(int A[],int n){
if(n==0){
return 0;
}
int j=0;
int num=0;
for(int i=1;i<n;i++){
if(A[j]==A[i]){
num++;
if(num<2){
A[++j]=A[i];
}
else{
A[++j]=A[i];
num=0;
}
}
}
return j+1;
}
}