incompatible conversion from int[] to int - java

class Solution {
public int removeDuplicates(int[] nums) {
int [] arr = new int[nums.length];
for(int i=0; i<nums.length; i++){
if(nums[i] != nums[i+1]){
arr[i] = nums[i];
}
}
return arr;
}
}
this is my code and I am having error ::
incompatible conversion from int[] to int.

Your return statement is returning the int array, but your declared return type is an int primitive. You should return the int array instead:
public int[] removeDuplicates(int[] nums)

The above solutions are right but i noticed another problem in your solution. Let's say that the array has 10 numbers.
You start from i = 0; and you continue until the i < array.legth. But in your comparison you compare num[i] and num [i+1]. So when i = 9 that is the last index of the array, the comparison will be if num[9] == num[10],so you will have a runtime error, because there is not index 10.
one think you can do is this:
class Solution {
public int[] removeDuplicates(int[] nums) {
int [] arr = new int[nums.length];
for(int i=0; i<nums.length-1; i++){
if(nums[i] != nums[i+1]){
arr[i] = nums[i];
}
}
return arr;
}
You got to change the array.length to array.length-1.
And if you still stuck that's an existed soltion for youe problem.
remove dublicates

Already said the return type must be int[] too.
public int[] removeDuplicates(int[] nums) {
if (nums.length == 0) {
return nums;
}
int[] arr = nums.clone();
int j = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[j]) {
++j;
arr[j] = arr[i];
}
}
return Arrays.copy(arr, j + 1);
}
The removal of consecutive duplicates must be done a bit different. Above a not so elegant solution. Not tested.

Related

Remove an Element in Array on Leet code. I am getting an error of getting incompatible types and I dont know whats wrong

Here is the question:
Given an integer array nums and an integer val, remove all
occurrences of val in nums in place. The relative order of the
elements may be changed.
Since it is impossible to change the length of the array in some
languages, you must instead have the result be placed in the first
part of the array nums.
More formally, if there are k elements after removing the duplicates,
then the first k elements of nums should hold the final result. It
does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of
nums.
Do not allocate extra space for another array. You must do this by
modifying the input array in-place with O(1) extra memory.
I've tried to remove the given target val by shifting the value to the end of the array index by iteration of nums.length-1 every time the val is found in the given array. I just want to know what's wrong with my approach.
Below is the code I've tried:
class Solution {
public int removeElement(int[] nums, int val) {
for (int i = 0; i < nums.length; i++) {
if (val == nums[i]) {
for (int j = i; j < nums.length - 1; j++) {
nums[j + 1] = nums[j];
}
break;
}
}
return nums;
}
}
Your algorithm correctly would be the following. The error was returning the array, but that was changed in-situ. You should have returned the new reduced length.
public int removeElement(int[] nums, int val) {
int k = nums.length;
for (int i = 0; i < k; i++) {
if (val == nums[i]) {
--k;
//for (int j = i; i < k; j++) {
// nums[j] = nums[j + 1];
//}
System.arraycopy(nums, i+1, nums, i, k-i);
--i; // Check the new nums[i] too
}
}
return k;
}
The for-j loop can be replaced with System.arraycopy (which handles overlapping of the same array too).
Or:
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < n; i++) {
if (val != nums[i]) {
nums[k] = nums[i];
++k;
}
}
return k;
}
This is my code in leetcode. Hope will help you
class Solution {
public int removeElement(int[] nums, int val) {
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
list.add(nums[i]);
}
}
for(int i=0;i<list.size();i++){
nums[i]= list.get(i);
}
return list.size();
}
}

How to return an array with the indexes of a certain int from another array

I'm a beginner Java student and I have been trying to write a method that lists all indexes of a certain int within an array. What I've done so far is store the value of that int at its corresponding index within another array but the best I can do is set the values of all other indexes that are not equal to the original int to -1.
I think I need to store the value i within the array and delete all the -1s but I don't know how to do this. By the way, these values are -1 because all my arrays in this program contain ints that are between 0-100. What would I do if possible ints within this array could be any number?
Also surely there is an easier or more efficient way of doing this.
public static int[] maxValueIndex(int[] arr, int targetValue, int x) {
int[] maxValue = new int[x];
for (int i = 0; i < arr.length; i++) {
if (arr[i] == targetValue) {
maxValue[i] = arr[i];
} else {
maxValue[i] = -1;
}
}
return maxValue;
}
If I understood your query correctly then you want an array with all the indices i such that arr[i]==targetValue. We can achieve this efficiently using any dynamic data structure. Like, use an ArrayList and keep adding all the desired indices one by one then convert the List to an array and return it.
Something like this:
List<Integer> index = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == targetValue)
index.add( i );
}
int[] maxValue = index.stream().mapToInt(Integer::intValue).toArray();
return maxValue;
If it is required to use arrays only to resolve this task, it may take two passes to create a compacted array containing only valid indexes:
Find the number of matches, and then create and fill a compact array
public static int[] getTargetIndexes(int targetValue, int ... arr) {
int n = arr.length;
int targetCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == targetValue) {
targetCount++;
}
}
int[] indexes = new int[targetCount];
for (int i = 0, j = 0; j <targetCount && i < n; i++) {
if (arr[i] == targetValue) {
indexes[j++] = i;
}
}
return indexes;
}
Create an array of the same length, fill it and then compact by using Arrays.copyOf:
public static int[] getTargetIndexes(int targetValue, int ... arr) {
int n = arr.length;
int[] indexes = new int[n];
int targetCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == targetValue) {
indexes[i] = i;
targetCount++;
} else {
indexes[i] = -1;
}
}
for (int i = 0, j = 0; j < targetCount && i < n; i++) {
if (indexes[i] > -1) {
indexes[j++] = i;
}
}
return Arrays.copyOf(indexes, targetCount); // truncate bad indexes
}
Also, the signature of the method uses vararg to pass the input array as a sequence of int -- the vararg argument int ... arr should be the last one then.
If Stream API can be used, the task may be resolved conveniently in a declarative way:
public static int[] getTargetIndexes(int targetValue, int ... arr) {
return IntStream.range(0, arr.length) // get stream of indexes
.filter(i -> arr[i] == targetValue) // keep only matching indexes
.toArray(); // build output array
}

Finding the same elements in an array and preventing duplicate counting

Given the following code:
public static int countSames(Object[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i].equals(a[k]) && i != k) {
count += 1;
break; //Preventing from counting duplicate times, is there way to replace this?
}
}
}
return count;
}
I would like to know if there is a solution which doesn't use break statement since I've heard its bad practice.
But without the break this method returns 6 instead of wanted 3 for array {'x', 'x', 'x'}.
If you're trying to find the number of unique elements in the array try using this approach as it has only one loop and hence efficient.
private static int findNUmberOfUnique(String[] array) {
Set<String> set=new HashSet<>();
for(int i=0;i<array.length;i++){
if(!set.contains(array[i])){
set.add(array[i]);
}
}
return set.size();
}
Let me know if I did not understand your requirement clearly.
You can always use a flag instead of break:
public static int countSames(Object[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
boolean found = false;
for (int k = 0; k < a.length && !found; k++) {
if (a[i].equals(a[k]) && i != k) {
count += 1;
found = true;
}
}
}
return count;
}
You can use a hashmap to find the same elements in an array and preventing duplicate counting.
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer>hs=new HashSet<Integer>();
for(int i:nums1)
hs.add(i);
HashSet<Integer>hs1=new HashSet<Integer>();
for(int j:nums2){
if(hs.contains(j)){
hs1.add(j);
}
}
int[] res=new int[hs1.size()];
int j=0;
for(int k:hs1)
res[j++]=k;
return res;
}
}

Java beginner here getting non zero numbers

I just want to ask why the temp in my method NonZeros does not change its elements even though I explicitly assign each element of temp whenever the source has a nonzero element. Here's my work.
package nonzeros;
public class NonZeros {
public static void main(String[] args) {
int [] B = {0,1,2,3,2};
int [] newone = NonZeros(B);
for(int q = 0; q < newone.length; q++){
System.out.println(newone[q]);
}
}
public static int[] NonZeros(int [] A){
int [] temp = new int[4];
for(int i = 0; i < A.length;i++){
if(A[i] != 0){
int j = 0;
temp[j] = A[i];
j++;
}
}
return temp;
}
}
Here's the result:
run:
2
0
0
0
However, the result should be: 1 2 3 2
Step one, count the non zero values. Step two, create the new array. Step three, fill it with non-zero values like
public static int[] NonZeros(int[] A) {
int count = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] != 0) {
count++;
}
}
int[] temp = new int[count];
int p = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] != 0) {
temp[p++] = A[i];
}
}
return temp;
}
Alternatively, use a lambda and filter like
public static int[] NonZeros(int[] A) {
return Arrays.stream(A).filter(i -> i != 0).toArray();
}
You declare int j=0; inside the loop, so all assignments go to the same place.
You need to move the j index outside of the loop:
public static int[] NonZeros(int [] A){
int [] temp = new int[4];
int j = 0;
for (int i=0; i < A.length; i++) {
if (A[i] != 0) {
temp[j] = A[i];
j++;
}
}
return temp;
}
The reason why your current output happens to be [2, 0, 0, 0] is that the final element in the input array is 2, and gets written to the first entry in the output array. In fact, currently all values are being written to the first entry of the output array.
The scope of the "j" variable that you are defining is the if block that contains it because you are declaring it inside the condition which results in you overwriting the first element in your temp array each time you find a non-zero number in the source while the rest of your temp elements remain unchanged.
The solution is to move the declaration of "j" to the body of the method just before the loop, that is:
public static int[] NonZeros(int [] A){
int [] temp = new int[4];
int j = 0;
for(int i = 0; i < A.length;i++){
if(A[i] != 0){
temp[j] = A[i];
j++;
}
}
return temp;
}

Creating a New Reverse Java Array

CodingBat > Java > Array-1 > reverse3:
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
public int[] reverse3(int[] nums) {
int[] values = new int[3];
for (int i = 0; i <= nums.length - 1; i++) {
for (int j = nums.length-1; j >= 0; j--) {
values[i] = nums[j];
}
}
return values;
}
I can't get this to work properly, usually the last int in the array, becomes every single int in the new array
You don't want a two-level loop. Just have one loop:
for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
values[i] = nums[j];
}
or, alternately, just don't track j sepearately, and do this:
for(int i = 0; i < nums.length; i++) {
values[i] = nums[nums.length - 1 - i];
}
Unless this is a homework, why not just use Apache ArrayUtils'
ArrayUtils.reverse(nums)
Never re-invent the wheel :)
The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.
public int[] reverse3(int[] nums) {
return new int[] { nums[2], nums[1], nums[0] };
}
See also:
CodingBat/Java/Array-1/reverse3
Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.
Firstly, while creating new array give it size of old array.
Next, when you're reversing an array, you don't need two loops, just one:
int length = oldArray.length
for(int i = 0; i < length; i++)
{
newArray[length-i-1] = oldArray[i]
}
You only want a single loop, but with indices going both ways:
public int[] reverse(int[] nums) {
int[] back = new int[nums.length];
int i,j;
for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
back[i] = nums[j];
return back;
}
public int[] reverse3(int[] nums) {
int rotate[]={nums[2],nums[1],nums[0]};
return rotate;
}
This code gives correct output:-
public int[] reverse3(int[] nums) {
int[] myArray=new int[3];
myArray[0]=nums[2];
myArray[1]=nums[1];
myArray[2]=nums[0];
return myArray;
}
I got this with Python.. So you can get the idea behind it
def reverse3(nums):
num = []
for i in range(len(nums)):
num.append(nums[len(nums) - i - 1])
return num
In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations.
First of all, very bad logic to have two loops for a simple swap algorithm such as :
public static void reverse(int[] b) {
int left = 0; // index of leftmost element
int right = b.length-1; // index of rightmost element
while (left < right) {
// exchange the left and right elements
int temp = b[left];
b[left] = b[right];
b[right] = temp;
// move the bounds toward the center
left++;
right--;
}
}//endmethod reverse
or simplified:
for (int left=0, int right=b.length-1; left<right; left++, right--) {
// exchange the first and last
int temp = b[left]; b[left] = b[right]; b[right] = temp;
}
Why go through all this pain, why dont you trust Java's built-in APIs and do something like
public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}
public int[] reverse3(int[] nums) {
int[] values = new int[nums.length];
for(int i=0; i<nums.length; i++) {
values[nums.length - (i + 1)]=nums[i];
}
return values;
}

Categories

Resources