remove duplicates in array using method - java

I'm trying to remove duplicate numbers from an array using a method but, unfortunately I can not solve it. This what I have done so far:
//method code
public static int[] removeDuplicates(int[] input){
int []r=new int[input.length];
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
if ((input[i]==input[j]) && (i != j)) {
return r;
}
}
}
return r;
}

The easiest thing to do is add all elements in a Set.
public static int[] removeDuplicates(int[] input){
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < input.length; i++) {
set.add(input[i]);
}
//by adding all elements in the Set, the duplicates where removed.
int[] array = new int[set.size()];
int i = 0;
for (Integer num : set) {
array[i++] = num;
}
return array;
}

You may do it this way:
public static int[] removeDuplicates(int[] input){
boolean[] duplicate = new boolean[input.length];
int dups = 0;
for (int i = 0; i < input.length; i++) {
if(duplicate[i])
continue;
for (int j = i + 1; j < input.length; j++) {
if ((input[i]==input[j])) {
duplicate[j] = true; // j is duplicate
++dups;
}
}
}
int[] r = new int[input.length] - dups;
int index = 0;
for(int i = 0; i < input.length; ++i)
r[index++] = input[i];
return r;
}
It can also be done in O(n log n). C++ code

If you don't want duplicates in your collection, well you shouldn't be using an Array in the first place. Use a set instead and you will never duplicates to remove in the first place.
If you only "sometimes" want no duplicates, well you better explain your situation further.

Related

Program which counts minimum of a two dimensional int array

I am trying to create a program, which counts the minimum of each dimension in a two dimensional array. So for ex. if i had an array:
int[][] test = {{1,2,3},{2,3,4},{4,5,6}}
the program would display: [1,2,4] - the minimum of each dimension.
For that I've created a method called minimum, which looks like this
static int[] minimum(int[][] arr) {
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
int min = arr[i][0];
if(arr[i][j] < min) {
min = arr [i][j];
result [i] = min;
} else{
}
}
}
return result;
}
But when i call out this method in my main, with a sample array
public static void main(String[] args) {
int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};
System.out.println(Arrays.toString(minimum(arr)));
}
The program displays [0,0,0,]. Do You have any clue where is the problem and how to fix it?
The problem is that if the first element in the array is min, it never gets recorded to the result array. Try:
static int[] minimum(int[][] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i][0];
for (int j = 1; j < arr[i].length; j++) {
if (arr[i][j] < result[i]) {
result[i] = arr[i][j];
}
}
}
return result;
}
Note that there needs to be at least one element per row in the input matrix for the above function; add a conditional or use Integer.MIN_VALUE to handle empty rows if you wish.
This should work. You reset the min to the first element every time. So you are basically comparing if there is any value smaller than the first one.
static int[] minimum(int[][] arr){
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++){
result[i] = Integer.MAX_VALUE;
for(int j = 0; j < arr[i].length; j++){
if(arr[i][j] < result[i]) {
result [i] = arr[i][j];
}
}
}
return result;
}

java | Return a reversed array by FOR loop

I am stuck with an exercise which tells me to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
But it is throwing out three exact same numbers.
You don't need a nested for loop - just iterate over the source array and fill the result array in the opposite order:
public int[] reverse(int[] nums) {
int len = nums.length;
int[] result = new int[len];
for (int i = 0; i < len; ++i) {
result[len - i - 1] = nums[i];
}
}
From a first look, your code should be more like this:
public int[] reverse3(int[] nums)
{
// initialize a second array with the same length
int[] nums2 = new int[nums.length];
// initialize the nums2 index
int index = 0;
// you only need one loop for this (since we'll be incrementing the index of nums2)
for (int i = nums.length - 1; i >= 0; i--) {
nums2[index] = nums[i];
index++;
}
return nums2;
}
Swap the symetric values in the array like this :
public static void reverse(int[] nums) {
for (int i = 0; i < nums.length / 2; i++) {
int temp = nums[i];
nums[i] = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = temp;
}
To reverse an array you only have to swap the elements until the midpoint:
public int[] reverse(int[] nums) {
int numsLength = nums.length;
for (int i = 0; i < numsLength / 2; i++) {
int temp = nums[i];
nums[i] = nums[numsLength - i - 1];
nums[numsLength - i - 1] = temp;
}
return nums;
}
This way is much more optimized.
Source: How do I reverse an int array in Java?
I am new to Java development and sorry if this question will be too
silly, but it seems like I am stuck with the exercise which tells me
to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
} } return nums2; }
But it is throwing out three exact same numbers. Could I please count
on some help? Thank you
Use one loop only. If you want to use 2 arrays(wich i do not see the point.) this will work:
int j = 0;
for(int i = nums.length -1; i >= 0; i--){
nums2[j] = nums[i];
j++;
}
But if you want to use only one array, you can do this:
for (int i = 0; i < nums.length/2; i++) {
int aux = nums[i];
nums[i] = nums[nums.length-i-1];
nums[nums.length-i-1] = aux;
}
There are so many efficient ways to do it but to make you understand i am gonna modify your own code
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = (nums.length-1) - i; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
or let's do a a little bit modification rather than using nums.length() again and again we can put it inside a variable
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
int length = nums.length;
for (int i = length - 1; i >= 0; i--) {
for (int j = (length-1) - i; j < length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
Remember it is not an efficient way but to make you understand i just modify the logic. Using nested loops like that will decrease the performance so better avoid it and try to do it in much more optimized way..

How to jump over a specific number in a loop

Didn't know how to call my Thread.
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[j] = numbers[j];
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++){
int k = i;
while(thisTuple[k] <= 0){
k++;
}
newTuple[i] = thisTuple[k];
}
this.tuple = newTuple;
}
This is my code snippet to create a new NaturalNumberTuple.
So this is the Array I want to use: int[] tT2 = {1,2,4,-4,5,4,4};
I only want to use natural numbers greater than 0 and my problem isn't to cut out the negative number but it is that my console is giving me this: Tuple(Numbers:1,2,4,5,5,4).
The problem is if I jump over that value which is negative with my while loop to get the higher (k) I will have to pass the same (k) in my for loop which I don't want to because I already got it in my Array. I hope you understand my problem.
Sorry for the bad english..
Edit: Can't use any methods from java itself like System.arrayCopy
You have an error in the first loop. Fixing it makes the second loop much simpler :
public NaturalNumberTuple(int[] numbers) {
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; // changed thisTuple[j] to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < newTuple.length; i++) {
newTuple[i] = thisTuple[i];
}
this.tuple = newTuple;
}
Of course, the second loop can be replaced with a call to System.arrayCopy.
I would change your while loop to an if that simply restarts the for loop. Say from this:
while(thisTuple[k] <= 0){
k++;
}
To something like this:
if (thisTuple[k] <= 0)
continue;
This stops you from adding the same number twice when you encounter a negative or zero number.
This code will solve you issue. The code is checked in the following link Tuple Exampple
int [] thisTuple = new int[numbers.length];
int count = 0;
for(int j = 0; j < numbers.length; j++){
if(numbers[j] > 0){
thisTuple[count] = numbers[j]; //Change to thisTuple[count]
count++;
}
}
int[] newTuple = new int[count];
for(int i = 0; i < count; i++){
newTuple[i] = thisTuple[i];
}

Modified Bubble Sort

I need to write an algorithm that will take an array of ints and find the k'th largest element in the array. The caveat here is that the runtime must be O(K*n) or better.
My teacher has made it clear this can be done with a modified bubble sort program, but I am unsure as to how I can modify the bubble sort without ruining it, as I would think it necessary to loop through every element of the array. Here is my code (just the shell of the program and an unmodified bubble sort):
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
}
}
}
return sorted[k-1];
}
Figured it out:
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = 0; i < A.length-1; i++)
{
for (int j = 0; j < A.length-i-1; j++)
{
if (sorted[j] > sorted[j+1])
{
temp = sorted[j];
sorted[j] = sorted[j+1];
sorted[j+1] = temp;
}
if(i == (k-1)) return A[A.length-i-1];
}
}
return sorted[A.length-k];
}
The the array has been sorted to the k-th largest element, it has found what it is looking for and can stop the sort and return.
I thought a modified bubble sort just exited early if the list was already sorted?
Wouldn't something like this suffice?
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
bool bSorted = TRUE;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
bSorted = FALSE;
}
}
if(bSorted)
break;
}
return sorted[k-1];
}

Nested loop extracting index values into new array

I am trying to extract specific index values from an array, and place them into a new array. The primary array values are as follows:
int a[] = {7, 8, 9, 9, 8, 7};
The call I am making to the method is as follows:
print(findAll (a,7));
print(findAll (a,2));
The method I am using is as follows:
public int[] findAll(int a[], int target)
{
int count = 0;
int i = 0;
int index = 0;
int spotIndex = 0;
for (i = 0; i < a.length; i++)
{
if (a[i] == target)
count = count + 1;
spotIndex = i;
}
int result[] = new int[count];
for (index = 0; index < count; index++)
{
result[index] = spotIndex;
index++;
}
return result;
}
The results should be:
{0, 5}
{}
My results are below; if I change the target argument I get the same results.
{5, 0}
{}
Thanks in advance....
Small advice:
for (index = 0; index < count; index++)
{
result[index] = spotIndex;
index++;
}
you index++ call double times. This is bad practice to use index in method scope, better is:
for (int index = 0; index < count; index++)
{
result[index] = spotIndex;
}
Notice that you put spotIndex (the same value) in all result elements.
Why you don't use List?
public Integer[] findAll(int a[], int target) {
List<Integer> result = new ArrayList<Integer>();
for (int i=0; i<a.length; i++) {
if (a[i] == target) {
result.add(i);
}
}
return result.toArray(new Integer[result.size()]);
}
spotIndex isn't serving the purpose you thought needed for.
for (i = 0; i < a.length; i++)
{
if (a[i] == target)
count = count + 1;
spotIndex = i; // spotIndex comes in for loop but not in if condition.
// and this gets modified at every step in loop.
// simply assigning value of i to it.
}
Instead the logic should be -
for (i = 0; i < a.length; i++)
{
if (a[i] == target)
count = count + 1;
}
count gives the number of times target is repeated. Now, create an array of size count to actually copy those element's index in to the array.
int result[] = new int[count];
int copyIndex = 0;
for (index = 0; index < a.length; index++)
{
if( a[index] == target )
{
result[copyIndex] = index ;
++copyIndex;
if( copyIndex == count )
return result ;
}
}
I don't see the use of this statement - spotIndex = i; in first loop.
Note: The logic assumes that search element( i.e., target ) is definitely present in the array. With slight modification though, we can return the indexes if element is present only.

Categories