Hello I want find the highest index n array. For example I have two arrays :
[1,2,3,0,-1] - should return 2 - index with max values
[] - should return -1 because array is empty
I have method:
public int findMax(int[] array){
int values =0;
for(int i=0; i<array.length; i++){
if(array == null)
{return -1;}
else(array{i}>values){
return i;
}
}
What i'm doing wrong?
Your program has logical as well as compilation errors. I guess you want to write a code like this,
public static void main(String[] args) throws IOException {
System.out.println(findMax(new int[] { 1, 2, 3, 0, -1 }));
System.out.println(findMax(new int[] {}));
}
public static int findMax(int[] array) {
if (array == null || array.length == 0) {
return -1;
}
int maxIndex = 0;
int maxNum = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxNum) {
maxNum = array[i];
maxIndex = i;
}
}
return maxIndex;
}
Like you expected, this gives following output,
2
-1
Suppose you want to find both maximum element and first index of maximum value.
Code for this:
public void findMax(int[] array){
int values =-99999999; //values is any large negative number
int index=-1;
if(array.length == 0)
{System.out.println("-1");}
for(int i=0; i<array.length; i++){
if(array[i]>values){
values=array[i];
index=i;
}
System.out.println("Max element is"+values +"and index is"+index);
}
}
Try this one:
public int findMax(int[] array) {
if (array == null || array.length == 0)
return -1;
int index = 0;
int max = -Integer.MAX_VALUE;
for (int i=0; i< array.length; i++) {
if (array[i] > max) {
index = i;
max = array[i];
}
}
return index;
}
public int findMax(int[] array){
return IntStream.range(0, array.length).boxed().max(Comparator.comparing(i -> array[i])).orElse(-1));
}
Related
Below code gives the length of longest increasing subsequence. Code works fine.
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
With the help of below code I want to print which array elements are part of the subsequence i.e [2,3,7,101],
How can I do it? Or do I need to write completely different code?
Is there any generic way to do for other problems to do like longest palindromic subsequence?
public int lengthOfLIS(int[] nums) {
return helper(nums, 0, Integer.MIN_VALUE);
}
public int helper(int[] arr, int i, int prev) {
if (i == arr.length)
return 0;
int include = 0;
if (arr[i] > prev) {
include = 1 + helper(arr, i + 1, arr[i]);
}
int exclude = helper(arr, i + 1, prev);
return Math.max(include, exclude);
}
public void longestIncreasingSubsequence(int[] numbers)
{
List<Integer> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < numbers.length; i++) {
temp.add(numbers[i]);
if ( i + 1 == numbers.length || numbers[i] > numbers[i + 1])
{
if(temp.size() >= result.size())
{
result.clear();
result.addAll(temp);
}
temp.clear();
}
}
System.out.println(result);
}
Try this
I got your point. Plz Check my new code
public void longestSubSequence(int[] nums)
{
int index=0;
List<Integer> result = new ArrayList<>();
while (index<nums.length)
{
int val=nums[index];
List<Integer> temp = new ArrayList<>();
temp.add(val);
for (int i = index+1; i < nums.length; i++) {
int currentVal = nums[i];
if (val < currentVal)
{
val= currentVal;
temp.add(currentVal);
}
}
if(temp.size()>= result.size())
{
result.clear();
result.addAll(temp);
temp.clear();
}
index++;
}
System.out.println(result);
}
Question : Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
What exactly does the return statement do here. What does return i + 1 mean here ?
The return i + 1 is returning how many unique integers are there. I believe this is a Leetcode problem, and since its in place, the int[] is passed in by reference, Leetcode wants to know how many numbers to check (you're supposed to put the unique numbers in the first i + 1 spots).
If you look at the question, it says:
Which means that you return the length of the array.
So, if you have the array [1,1,2,3,4,4], you would turn that into [1,2,3,4,...], where the ... is the rest of the array. However, you return 4 because the length of the new array should be 4.
Hope this clears things up for you!
Your question has been already answered here; in addition to that, we can also start from zero and remove the first if statement:
Test with a b.java file:
import java.util.*;
class Solution {
public static final int removeDuplicates(
final int[] nums
) {
int i = 0;
for (int num : nums)
if (i == 0 || num > nums[i - 1]) {
nums[i++] = num;
}
return i;
}
}
class b {
public static void main(String[] args) {
System.out.println(new Solution().removeDuplicates(new int[] { 1, 1, 2}));
System.out.println(new Solution().removeDuplicates(new int[] { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4}));
}
}
prints
2
5
I tried in this easy way. Here Time complexity is O(n) and space
complexity: O(1).
static int removeDuplicates(int[] nums){
if(nums.length == 0) {
return 0;
}
int value = nums[0];
int lastIndex = 0;
int count = 1;
for (int i = 1; i < nums.length; i++) {
if(nums[i] > value) {
value = nums[i];
lastIndex = lastIndex+1;
nums[lastIndex] = value;
count++;
}
}
return count;
}
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
if (n == 0 || n == 1)
return n;
int j = 0;
for (int i=0; i<n-1; i++)
if (nums[i]!= nums[i+1])
nums[j++] = nums[i];
nums[j++]=nums[n-1];
return j;
}
}
public class RemoveDuplicateSortedArray {
//Remove Duplicates from Sorted Array
public static void main(String[] args) {
int[] intArray = new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
int count = extracted(intArray);
for (int i = 0; i < count; i++) {
System.out.println(intArray[i]);
}
}
private static int extracted(int[] intArray) {
int size = intArray.length;
int count = 1;
if (size == 1) {
return 1;
} else if (size == 2) {
if (intArray[0] == intArray[1]) {
return 1;
} else {
return 2;
}
} else {
for (int i = 0, j = i + 1; j < size; j++) {
if (intArray[i] < intArray[j]) {
i++;
intArray[i] = intArray[j];
count++;
}
}
return count;
}
}
}
I am trying to print an output that would find the max number and also print the index number of the array as well. I am able to print the max number but I am unable to print the index number.
public static int findMax(int[] allNumbers) {
int maxValue = allNumbers[0];
for (int i = 1; i < allNumbers.length; i++) {
if (allNumbers[i] > maxValue) {
maxValue = allNumbers[i];
}
}
return (int) maxValue;
}
my array:
int[] allNumbers = new int[inpNum];
I can call the max number with the following
findMax(number)
You can return an array of the max value and index:
public static int[] findMax(int[] allNumbers) {
int maxValue = allNumbers[0];
int index = 0;
for (int i = 1; i < allNumbers.length; i++) {
if (allNumbers[i] > maxValue) {
maxValue = allNumbers[i];
index = i;
}
}
return new int[] {maxValue , index};
}
I have written the following code and am now trying to figure out the best way to achieve what is explained in the four comments:
Integer[] expectedValues = new Integer[4];
for (int i = 0; i <= 3; i++) {
expectedValues[i] = getExpectedValue(i);
}
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
// return index of highest value in expectedValues
} else if (choice <= intelligence * 2) {
// return index of 2nd highest value in expectedValues
} else if (choice <= intelligence * 3) {
// return index of 3rd highest value in expectedValues
} else {
// return index of lowest value in expectedValues
}
What would be an elegant way o doing so? I do not need to keep expected values as an array - I am happy to use any data structure.
You could create a new array containing the indices and sort on the values - in semi-pseudo code it could look like this (to be adapted):
int[][] valueAndIndex = new int[n][2];
//fill array:
valueAndIndex[i][0] = i;
valueAndIndex[i][1] = expectedValues[i];
//sort on values in descending order
Arrays.sort(valueAndIndex, (a, b) -> Integer.compare(b[1], a[1]));
//find n-th index
int n = 3; //3rd largest number
int index = valueAndIndex[n - 1][0];
If you want to work with simple arrays, maybe this might be a solution:
public static void main(String[] args) {
int[] arr = new int[] { 1, 4, 2, 3 };
int[] sorted = sortedCopy(arr);
int choice = randomNumGenerator.nextInt(100) + 1;
if (choice <= intelligence) {
System.out.println(findIndex(arr, sorted[3])); // 1
} else if (choice <= intelligence * 2) {
System.out.println(findIndex(arr, sorted[2])); // 3
} else if (choice <= intelligence * 3) {
System.out.println(findIndex(arr, sorted[1])); // 2
} else {
System.out.println(findIndex(arr, sorted[0])); // 0
}
}
static int[] sortedCopy(int[] arr) {
int[] copy = new int[arr.length];
System.arraycopy(arr, 0, copy, 0, arr.length);
Arrays.sort(copy);
return copy;
}
static int findIndex(int[] arr, int val) {
int index = -1;
for (int i = 0; i < arr.length; ++i) {
if (arr[i] == val) {
index = i;
break;
}
}
return index;
}
You can "wipe out" the highest value n-1 times. After this the highest value is the n-th highest value of the original array:
public static void main(String[] args) {
int[] numbers = new int[]{5, 9, 1, 4};
int n = 2; // n-th index
for (int i = 0; i < n - 1; ++i) {
int maxIndex = findMaxIndex(numbers);
numbers[maxIndex] = Integer.MIN_VALUE;
}
int maxIndex = findMaxIndex(numbers);
System.out.println(maxIndex + " -> " + numbers[maxIndex]);
}
public static int findMaxIndex(int[] numbers) {
int maxIndex = 0;
for (int j = 1; j < numbers.length; ++j) {
if (numbers[j] > numbers[maxIndex]) {
maxIndex = j;
}
}
return maxIndex;
}
The complexity is O(n * numbers.length).
So I'm writing a method to calculate mode of a sorted array. But when i print out the mode value, it always comes out as 0.00, and i tried to fix it but could't.
Here's my code for this method:
(numRead is the passed array, num is the array length that actually have values)
public static void modeCalc(double[] numRead, int num)
{
double maxValue = numRead[0];
int maxCount = 0;
for (int i = 0; i < numRead.length; i++)
{
int count = 0;
for (int j = 0; j < numRead.length; j++)
{
if (numRead[j] == numRead[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = numRead[i];
}
}
return maxValue;
}
Any help is much appreciated!
This should work. You need to return a double, and you need to use num.
class ModeArray
{
public static void main(String[] args) {
double[] numRead = { 1, 2, 3, 3, 4, 4, 4, 5, 0, 0, 0, 0, 0 };
System.out.println(modeCalc(numRead, 8));
}
public static double modeCalc(double[] numRead, int num) {
double maxValue = numRead[0];
int maxCount = 0;
for (int i = 0; i < num; i++) {
int count = 0;
for (int j = 0; j < num; j++) {
if (numRead[j] == numRead[i]){
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxValue = numRead[i];
}
}
return maxValue;
}
}
If you know the array is sorted, you should use this information.
public static double modeCalc(double[] numRead, int num) {
double maxValue = numRead[0];
double lastValue = maxValue;
int count = 1;
int maxCount = 1;
for (int i = 1; i < num; i++) {
if (numRead[i] == lastValue) {
count++;
} else {
count = 1;
lastValue = numRead[i];
}
if (count > maxCount) {
maxCount = count;
maxValue = lastValue;
}
}
return maxValue;
}
PS: Please don't use if-statement without braces. It makes it easier to add bugs, and harder to find them.
a cursory glance suggests that your array has more 0 values at the end of the sorted data and these become the mode. here is what appears to be the problem, it is stated that numRead is the sorted array, but it has only num values of significance. the loops search the array to the end, not for the number of elements that have good values. change numRead.length to num and see if that helps. also, try passing a full array (no empty elements) and see if it works any better. it is likely that the empty elements are initialized to zero and that there are more of these than any other value.