I'm trying to remove every instance of value from an array of integers, and return the length of the new array of integers.The input is [3,2,2,3], with val being 3. The output should be [2,2], with length 2. I keep getting [3,2], but I am removing val through an array.
class Solution {
public int removeElement(int[] nums, int val) {
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
list.add(nums[i]);
}
if(list.isEmpty()) {
return 0;
}
for(int i = 0; i < list.size(); i++) {
if(list.get(i) == val) {
list.remove(i);
}
}
return list.size();
}
}
When you remove the first 3 you will have i=0 and next the array list will resize, so when you delete you need to do i - -.
class Solution {
public int removeElement(int[] nums, int val) {
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
list.add(nums[i]);
}
if(list.isEmpty()) {
return 0;
}
for(int i = 0; i < list.size(); i++) {
if(list.get(i) == val) {
list.remove(i);
i--;
}
}
return list.size();
}
}
You haven’t shown any printing code but I assume you print nums based on the number returned by this method. That means you never change nums in any way and just print the first n numbers from there. You need to return the modified array instead of just the length.
You do not need to call remove at all (while removing like you do, it is okay, but for example, if you do this in a foreach cycle, it would crash on ConcurrentModificationException. Instead, you can determine whether to add item to the resulting list or not inside the first for loop (which is in my opinion safer):
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
list.add(nums[i]);
}
}
return list.size();
(I know that this does not answer your question directly)
Related
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();
}
}
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
}
I keep getting a IndexOutOFBoundsException and i cant seem to find where. Ive spent ages trying to figure this out. Any help would be appreciated. Thanks
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
if(nums.length < 2){
return new ArrayList<Integer>();
}
List<Integer> ret = new ArrayList<Integer>(nums.length);
for(int i=0; i < nums.length; i++){
ret.set(i,i);
}
for(int i=0; i < nums.length; i++){
ret.set(nums[i]-1, nums[i]);
}
for(int i=0; i < nums.length; i++){
if(ret.get(i) == 0){
ret.set(i, i+1);
}
else{
ret.remove(i);
}
}
return ret;
}
}
for(int i=0; i < nums.length; i++){
ret.set(nums[i]-1, nums[i]);
}
There you set the nums[i]-1s index to nums[i] but it will throw the error if nums[i] is either smaller or equal to 0 or higher than the length.
As the other answer from #Bahij.Mik states(make sure to upvote it), there are no elements in the list at this point.
You may want to use add() instead of set() here.
Note that new ArrayList<>(number) will create a new ArrayList with an initial space for n elements, it will not fill the elements like it would happen with an array(not even with null)
Also, in
for(int i=0; i < nums.length; i++){
if(ret.get(i) == 0){
ret.set(i, i+1);
}
else{
ret.remove(i);
}
}
you are removing elements while iterating over the ArrayList.
This will reduce the size of the ArrayList and you will iterate out of the bounds if you removed an element at some point.
There are several issues in your code, first thing that comes to sight is that when you are instantiating your arraylist with
List<Integer> ret = new ArrayList<Integer>(nums.length);
You are just setting the list's initial capacity not the size, so you can't set elements at specific indices, instead you need to add elements to the list then you can modify them at said indices, so instead of the ret.set(i, i) use ret.add(i).
Here is a solution
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> ret = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
int index = Math.abs(nums[i]) - 1;
if(nums[index] > 0 ){
nums[index] *= -1;
}
}
for(int j = 1; j <= nums.length; j++){
if(nums[j-1] > 0 ){
ret.add(j);
}
}
return ret;
}
}
Hi I'm trying to figure out how to use BubbleSort in Java and my code is erroring and I don't know why
import java.util.ArrayList;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = arr.size();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr.get(j) > arr.get(j+1))
{
int temp = arr.get(j);
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
When I get to arr.get(j) = arr.get(j+1); and arr.get(j+1) = temp; the left side errors saying "The left-hand side of an assignment must be a variable." can anyone help me fix this?
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
You're trying to assign a value to the result of a method call.
You just can't do this. You can only assign to a local variable, a field in the current class, a field access (e.g. foo.bar = ...) or an array element (e.g. foo[0] = ...).
Instead, you should use set to update a list element:
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);
For the specific case of swapping two elements around in a list, you can instead use Collections.swap:
Collections.swap(arr, j, j+1);
You are doing several things wrong.
The obivous get and set issues already mentioned.
The fact that your are sorting an empty list. You pass in nums but sort the one you create which is empty.
You should use a boolean to prevent unnecessary repeats of the outer loop. Think of it like this, if you don't make a swap on the first iteration of the outer loop, then you won't swap on subsequent iterations.
And one style suggestion. Don't use loops or if statements without {}. Even if they only contain a single line of code. You will be less likely to make coding errors if you do so.
Try the following:
public static void BubbleSort(List<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
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;
}
}