[英]How do I limit draggable area? it functions on top and left side, but not on the right side and bottom
[英]count of odd elements of left side and right side please modify my code without exceeding the time limit
我的代碼是 O(n^2),請減少為 O(n)。 我的問題是左側奇數和右側奇數的計數。 如果兩邊(左右)相等,則打印相應的元素,否則打印“-1”。 我的代碼邏輯是正確的,它執行正常的文本案例,但它無法執行大值的文本案例。它顯示錯誤為“超出時間”。它超出了編譯器的時間限制。我想減少時間我的代碼限制。
例如:我的輸入是 4 1 4 3 8 而我的輸出是:-1 4 -1 -1
示例 2:我的輸入是 6 1 3 4 8 5 7 而我的輸出是:-1 -1 4 8 -1 -1
在此處輸入代碼
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int temp = 0;
int count = 0;
int flag = 0;
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
temp = a[i];
for (int j = 0; j < i; j++) {
if (a[j] % 2 != 0) {
count++;
}
}
for (int k = i + 1; k < n; k++) {
if (a[k] % 2 != 0) {
flag++;
}
}
if (count == flag) {
System.out.print(temp + " ");
} else {
System.out.print("-1 ");
}
count = 0;
flag = 0;
}
}
我還沒有測試過,但它應該可以工作。
你的算法是 O(n^2) 而這個是 O(n)。
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
}
int total = 0;
for(int i=0;i<n;i++) {
if(a[j]%2!=0) {
total++;
}
}
int leftTotal = 0;
for(int i=0;i<n;i++) {
int k = a[i];
if (k%2!=0) {
leftTotal++;
}
if (leftTotal = (total-leftTotal)) {
System.out.println(k);
} else {
System.out.println(k);
}
}
}
enter code here
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int a[]=new int[n],flag=0,count=0;
for(int i=0;i<n;i++) {
a[i]=s.nextInt();
if(a[i]%2!=0)
count++;
}
for(int i=0;i<n;i++) {
if(a[i]%2!=0)
count--;
if(flag==count)
System.out.print(a[i]+" ");
else
System.out.print("-1 ");
if(a[i]%2!=0)
flag++;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.