Home > other >  How to Convert and get Negative number in to positive Numbers in an Integer Array.?
How to Convert and get Negative number in to positive Numbers in an Integer Array.?

Time:12-06

I had to print greatest of three numbers in an array in which negative numbers which consists of highest value need to be converted to positive.for example: input: int[] nums={3,5,8,1,2,0,-10,-20}; output: {20,10,8}.

private List<Integer> largestThreeNums(int[] nums) {
            
            Arrays.sort(nums);
            int x=nums.length;
            return Arrays.asList(Math.abs(nums[x-1]),Math.abs(nums[x-2]),Math.abs(nums[x-3]));
            
            

        }

CodePudding user response:

To solve this problem, you can first iterate over the array and find the maximum negative number. Then, you can convert this number to positive and store it in a new array. Finally, you can sort this new array in descending order and print the elements.

Here is some sample code that shows how you could implement this:

// Find the maximum negative number in the array
int maxNegative = Integer.MIN_VALUE;
for (int num : nums) {
  if (num < 0 && num > maxNegative) {
    maxNegative = num;
  }
}

// Convert the maximum negative number to positive
maxNegative = -maxNegative;

// Create a new array with the converted negative number and the other elements in the original array
int[] result = new int[nums.length];
result[0] = maxNegative;
for (int i = 1; i < nums.length; i  ) {
  result[i] = nums[i - 1];
}

// Sort the new array in descending order
Arrays.sort(result);

// Print the elements of the new array
for (int num : result) {
  System.out.println(num);
}

Note that this code assumes that the input array nums has at least one negative number. If the array doesn't have any negative numbers, you could handle this case by simply sorting the original array in descending order and printing the elements.

CodePudding user response:

If I understand the question, it is to find the three largest absolute values of the items. Here is a solution using Java streams:

Arrays.stream(nums)
    .map(Math::abs)
    .sorted(Comparator.reverseOrder())
    .limit(3)
    .toList();

This can be read as: stream the items, convert each to its absolute value, sort from largest to smallest, get the first three and covert to a list.

CodePudding user response:

Approach 1

You can do this using java streams with following logic.

  • first you use map() to get absolute values

  • then you sort absolute number list using sorted()

  • then you get first three numbers using limit()

      private List<Integer> largestThreeNums(Integer[] nums) {
          List<Integer> numList = Arrays.asList(nums);
          return numList.stream().map(num -> Math.abs(num)).sorted(Comparator.reverseOrder()).limit(3).collect(Collectors.toList());
      }
    

Approach 2

But the performance of 1st approach will be very low for larger data set because we are sorting complete array. In such scenario you can use following logic.

    private List<Integer> largestThreeNumsWithoutSorting(Integer[] nums) {
    List<Integer> numList = Arrays.asList(nums);
    List<Integer> absNumList = numList.stream().map(num -> Math.abs(num)).collect(Collectors.toList());

    int largest = absNumList.get(0);
    int secondLargest = absNumList.get(0);
    int thirdLargest = absNumList.get(0);

    for (int num: absNumList) {
        if(num >= largest) {
            thirdLargest = secondLargest;
            secondLargest = largest;
            largest = num;
        } else if (num >= secondLargest) {
            thirdLargest = secondLargest;
            secondLargest = num;
        } else if (num >= thirdLargest) {
            thirdLargest = num;
        }
    }

    return Arrays.asList(largest, secondLargest, thirdLargest);
}
  • Related