Como encontrar o terceiro maior número em uma matriz
Fonte: Dev.to Temos um problema para resolver: você recebe um array não classificado de inteiros. Como encontrar o terceiro maior número em um array? Nota: A matriz contém valores duplicados e valores negativos, e este código também deve funcionar se o comprimento da matriz aumentar N vezes. A solução é dada em Java:Exemplo 1: array não classificado com valores negativos
Entrada: [87, 99, -14, 05, 46, 54] Código:public class ThirdLargestNumInArray {
public static void main(String[] args) {
/*
* unsorted Array with duplicate and negative values
*/
Integer arr[] = { 87, 99, -14, 05, 46, 54 };
/* Variable initialization */
int largest = 0, secondLargest = 0, thirdLargest = 0;
/* Condition to find */
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
/*
* if condition is true assign large value to second large value
*/
secondLargest = largest;
/* assign new large value */
largest = arr[i];
} else if (arr[i] > secondLargest) {
/*
* if condition is true assign second large value to third large value
*/
thirdLargest = secondLargest;
/* assign new second large value */
secondLargest = arr[i];
} else if (arr[i] > thirdLargest) {
/*
* if condition is true the third largest value will be assigned
*/
thirdLargest = arr[i];
}
}
/* Print the values */
System.out.println("Largest = " + largest);
System.out.println("Second Largest = " + secondLargest);
System.out.println("Third Largest = " + thirdLargest);
}
}
Conclusão:
-
Conforme mencionado acima, o array é inicializado com valores positivos e negativos.
-
Inicializamos variáveis para armazenar o maior, o segundo maior e o terceiro maior valor, respectivamente. Nota: As variáveis são inicializadas com 0 para um caso especial: se o terceiro elemento máximo não estiver no array, ele retornará 0.
-
Repetimos o loop N (o comprimento da matriz) várias vezes para encontrar os três maiores valores.
-
Se a condição for atribuir o maior valor ao segundo valor grande e inicializar um novo valor grande no array.
A primeira condição elseif é atribuir o segundo valor grande ao terceiro valor grande e inicializar um novo segundo valor grande na matriz.
A segunda condição elseif é atribuir o terceiro valor grande na matriz.
-
Finalmente, imprimimos as variáveis.
Exemplo 2: array não classificado com valores negativos e duplicados
Entrada: [77, 101, 95, 14, 05, 46, -47, 94, 00, 95, 52, 86, 36, -54, 94, 89] Código:import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
public class ThirdLargestNumInSet {
public static void main(String[] args) {
/*
* unsorted Array with duplicate and negative values
*/
Integer arr[] = { 77, 101, 14, 05, 46, -47, 94, 00, 95, 52, 86, 36, -54, 94, 89 };
/* Variable initialization */
int largest = 0, secondLargest = 0, thirdLargest = 0;
/*
* using LinkedHashSet - Map to remove duplication in Array
*/
Set<Integer> newSet = new LinkedHashSet<>();
for (int i = 0; i < arr.length; i++) {
newSet.add(arr[i]);
}
/* Condition to find */
for (Integer i : newSet) {
if (i > largest) {
/*
* if condition is true assign large value to second large value
*/
secondLargest = largest;
/* assign new large value */
largest = i;
} else if (i > secondLargest) {
/*
* if condition is true assign second large value to third large value
*/
thirdLargest = secondLargest;
/* assign new second large value */
secondLargest = i;
} else if (i > thirdLargest) {
/*
* if condition is true the third largest value will be assigned
*/
thirdLargest = i;
}
}
/* Print the values */
System.out.print("Largest = " + largest);
System.out.print("\nSecond Largest = " + secondLargest);
System.out.print("\nThird Largest = " + thirdLargest);
}
}
Conclusão:
Outra solução:
Podemos usar o algoritmo de classificação por bolha (classificação da ordem mais baixa para a mais alta) para classificar o array e encontrar o maior valor do array. Entrada: [87, 99, 14, 05, 46, 54] Código:import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
public class Main {
public static void bubblesort(Integer[] arr) {
int n = arr.length;
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
Integer[] arr = { 87, 99, 14, 05, 46, 54 };
bubblesort(arr);
System.out.print("array after sorting : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
int n = arr.length;
int max = arr[n - 3];
System.out.println("\n3rd largest value: " + max);
}
}
Conclusão:
Reverter uma string em Java
Fonte: Dev.toPrograma Java para reverter uma string usando StringBuilder
Explicação: Strings são objetos em Java que são apoiados internamente por uma matriz de caracteres. Strings são imutáveis porque arrays são imutáveis (fechados para modificação). Cada vez que você faz alterações em uma linha, uma nova linha é criada. No nosso caso estamos usando StringBuilder que é mutável. Nota: Também podemos usar a classe StringBuffer . Código:public class ReverseStringBuilder {
public static void main(String[] args) {
/* String is immutable */
String name = "Palindrome";
/* Create StringBuilder(mutable) object */
StringBuilder s1 = new StringBuilder();
/* Using append() and reverse() in StringBuilder */
s1.append(name);
s1 = s1.reverse();
/* Print the reverse */
System.out.println(s1);
}
}
Conclusão:
-
Crie um objeto da classe String e inicialize-o.
-
Crie um objeto da classe construtor de string .
-
Use as funções internas do construtor de strings append() e reverse() .
-
Imprima o objeto construtor de string .
Programa Java para reverter uma string sem usar a função integrada String reverse()
Método 1
Explicação: A função toCharArray() é usada para converter esta string em uma matriz de caracteres. Depois disso, usaremos um loop for para percorrer cada caractere na ordem inversa e obter a saída de cada caractere. Código:public class Reverse {
public static void main(String[] args) {
/* String is immutable */
String name = "Palindrome";
/* Using toCharArray() function */
char[] ch = name.toCharArray();
/* Temp string */
String rev = "";
/* Iterating for loop in reverse to store */
for (int i = ch.length - 1; i >= 0; i--) {
/* Concatenating Strings */
rev += ch[i];
}
/* Print the reverse */
System.out.println(rev);
}
}
Conclusão:
-
Crie um objeto da classe String e inicialize-o.
-
Crie uma matriz de caracteres e chame a função toCharArray() com um objeto String .
-
Crie um objeto String para uma variável temporária.
-
Repita o loop for ao contrário para obter cada caractere na ordem inversa.
-
Concatene cada caractere em uma variável Temp .
-
Digite Temperatura .
Método 2
Explicação: Usando um loop for , imprimimos uma string na ordem inversa. Por outro lado, o método charAt(index) retorna o caractere em qualquer índice fornecido. O caractere será concatenado após cada iteração para alterar a variável string. Código:public class ReverseCharAt {
public static void main(String[] args) {
/* String is immutable */
String name = "Palindrome";
/* Temp string */
String rev = "";
/* Iterating for loop in reverse to store */
for (int i = name.length() - 1; i >= 0; i--) {
/* Concatenating Strings */
rev = rev + name.charAt(i);
}
/* Print the reverse */
System.out.println(rev);
}
}
Conclusão:
-
Criando um objeto da classe String e inicializando-o.
-
Crie um objeto String para uma variável temporária.
-
Repetir o loop for na ordem inversa para obter cada caractere na ordem inversa.
-
Concatene cada caractere em uma variável Temp chamando a função charAt() .
-
Imprimimos Temp .
GO TO FULL VERSION