JavaRush /Java Blog /Random EN /Coffee break #110. We solve the problem of how to find th...

Coffee break #110. We solve the problem of how to find the third largest number in an array. Reverse a string in Java

Published in the Random EN group

How to find the third largest number in an array

Source: Dev.to We have a problem to solve: You are given an unsorted array of integers. How to find the third largest number in an array? Note: The array contains both duplicate values ​​and negative values, and also this code should work if the length of the array increases by N times. Coffee break #110.  We solve the problem of how to find the third largest number in an array.  Reverse a string in Java - 1The solution is given in Java:

Example 1: Unsorted array with negative values

Input: [87, 99, -14, 05, 46, 54] Code:
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);

    }
}
Conclusion:
Largest = 99 Second Largest = 87 Third Largest = 54
Explanation:
  1. As mentioned above, the array is initialized with both positive and negative values.

  2. We initialize variables to store the largest, second largest, and third largest value respectively. Note: The variables are initialized to 0 for one special case: if the third maximum element is not in the array, it will return 0.

  3. We repeat the loop N (the length of the array) a number of times to find the three largest values.

  4. If the condition is to assign the largest value to the second large value and initialize a new large value in the array.

    The 1st elseif condition is to assign the second big value to the third big value and initialize a new second big value in the array.

    The 2nd elseif condition is to assign the third large value in the array.

  5. Finally, we print the variables.

Example 2: Unsorted array with negative and duplicate values

Input: [77, 101, 95, 14, 05, 46, -47, 94, 00, 95, 52, 86, 36, -54, 94, 89] Code:
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);
    }
}
Conclusion:
Largest = 101 Second Largest = 95 Third Largest = 94
Explanation: The pseudo code used in both codes is the same, the only difference in example 2 is that we are using LinkedHashSet. It is a Java collection in which we store unique objects which results in removing duplicate values ​​in the array.

Another solution:

We can use the bubble sort algorithm (sorting from lowest to highest order) to sort the array and find the largest value of the array. Input: [87, 99, 14, 05, 46, 54] Code:
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);
    }

}
Conclusion:
array after sorting : 5 14 46 54 87 99 3rd largest value: 54

Reverse a string in Java

Source: Dev.to

Java program to reverse a string using StringBuilder

Explanation: Strings are objects in Java that are internally backed by an array of characters. Strings are immutable because arrays are immutable (closed to modification). Every time you make changes to a row, a new row is created. In our case we are using StringBuilder which is mutable. Note: We can also use the StringBuffer class . Code:
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);

    }

}
Conclusion:
emordnilaP
Sequencing:
  1. Create an object of the String class and initialize it.

  2. Create an object of the string builder class .

  3. Use the built-in string builder append() and reverse() functions .

  4. Print the string builder object .

Java program to reverse a string without using the built-in function String reverse()

Method 1

Explanation: The toCharArray() function is used to convert this string to a character array. After this, we will use a for loop to go through each character in reverse order and get the output for each character. Code:
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);

    }

}
Conclusion:
emordnilaP
Sequencing:
  1. Create an object of the String class and initialize it.

  2. Create a character array and call the toCharArray() function with a String object .

  3. Create a String object for a temporary variable.

  4. Repeat the for loop in reverse to get each character in reverse order.

  5. Concatenate each character into a Temp variable .

  6. Type Temp .

Method 2

Explanation: Using a for loop , we printed a string in reverse order. On the other hand, the charAt(index) method returns the character at any given index. The character will be concatenated after each iteration to change the string variable. Code:
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);

    }

}
Conclusion:
emordnilaP
Sequencing:
  1. Creating an object of the String class and initializing it.

  2. Create a String object for a temporary variable.

  3. Repeating the for loop in reverse order to get each character in reverse order.

  4. Concatenate each character into a Temp variable by calling the charAt() function .

  5. We print Temp .

Special Note: You may be familiar with the reverse function, but the goal here is to explore the capabilities of StringBuilder and how you can optimize your code without the reverse function. Hope this helps someone in the future!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION