Я хотел бы знать, имеют ли Math.min и Math.max в Java одинаковую временную сложность, поскольку моя задача была отклонена, поскольку ее выполнение заняло слишком много времени.
Я работал над проблемой, которая требовала добавления общие элементы в 3 отсортированных массивах по возрастанию.
Правильное и оптимизированное решение предполагает, что, когда один из A,B[j] или C[k] является минимальным из трех, индекс массива, содержащего этот min должно увеличиваться на единицу.
Мой подход заключался в том, что мы должны увеличивать не только тогда, когда элемент равен min. Но каждый индекс массива элемента, который не является максимальным, должен быть увеличен
вот оптимизированное решение:
ArrayList commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// Initialize three pointers for each array
int i = 0, j = 0, k = 0;
// Initialize an arraylist to store the common elements
ArrayList res = new ArrayList();
// Initialize a variable to store the last checked element
int last = Integer.MIN_VALUE;
// Loop until any of the three arrays reaches its end
while (i < n1 && j < n2 && k < n3)
{
// If the current elements of all three arrays are equal and not the same as the last checked element
if (A == B[j] && A == C[k] && A != last)
{
// Add the common element to the result arraylist
res.add (A);
// Update the last checked element
last = A;
// Move to the next element in each array
i++;
j++;
k++;
}
// If the current element of array A is the smallest, move to the next element in array A
else if (Math.min (A, Math.min(B[j], C[k])) == A) i++;
// If the current element of array B is the smallest, move to the next element in array B
else if (Math.min (A, Math.min(B[j], C[k])) == B[j]) j++;
// If the current element of array C is the smallest, move to the next element in array C
else k++;
}
вот мое решение:
public static ArrayList commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// code here
ArrayList res=new ArrayList ();
int i=0;
int j=0;
int k=0;
long last=Long.MIN_VALUE;
while(i
Подробнее здесь: https://stackoverflow.com/questions/784 ... d-math-max
Временная сложность Math.min и Math.max ⇐ JAVA
Программисты JAVA общаются здесь
1715211523
Anonymous
Я хотел бы знать, имеют ли Math.min и Math.max в Java одинаковую временную сложность, поскольку моя задача была отклонена, поскольку ее выполнение заняло слишком много времени.
Я работал над проблемой, которая требовала добавления общие элементы в 3 отсортированных массивах по возрастанию.
Правильное и оптимизированное решение предполагает, что, когда один из A[i],B[j] или C[k] является минимальным из трех, индекс массива, содержащего этот min должно увеличиваться на единицу.
Мой подход заключался в том, что мы должны увеличивать не только тогда, когда элемент равен min. Но каждый индекс массива элемента, который не является максимальным, должен быть увеличен
вот оптимизированное решение:
ArrayList commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// Initialize three pointers for each array
int i = 0, j = 0, k = 0;
// Initialize an arraylist to store the common elements
ArrayList res = new ArrayList();
// Initialize a variable to store the last checked element
int last = Integer.MIN_VALUE;
// Loop until any of the three arrays reaches its end
while (i < n1 && j < n2 && k < n3)
{
// If the current elements of all three arrays are equal and not the same as the last checked element
if (A[i] == B[j] && A[i] == C[k] && A[i] != last)
{
// Add the common element to the result arraylist
res.add (A[i]);
// Update the last checked element
last = A[i];
// Move to the next element in each array
i++;
j++;
k++;
}
// If the current element of array A is the smallest, move to the next element in array A
else if (Math.min (A[i], Math.min(B[j], C[k])) == A[i]) i++;
// If the current element of array B is the smallest, move to the next element in array B
else if (Math.min (A[i], Math.min(B[j], C[k])) == B[j]) j++;
// If the current element of array C is the smallest, move to the next element in array C
else k++;
}
вот мое решение:
public static ArrayList commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// code here
ArrayList res=new ArrayList ();
int i=0;
int j=0;
int k=0;
long last=Long.MIN_VALUE;
while(i
Подробнее здесь: [url]https://stackoverflow.com/questions/78451563/time-complexity-of-math-min-and-math-max[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия