寻找数组中最后一个3的倍数,使用Java。

huangapple go评论84阅读模式
英文:

Find the Last Multiple of 3 in an Array using Java

问题

写一个方法,返回数组中最后一个值的索引,该值是3的倍数。

例如,在数组中

[4, 7, 9, 7, 12]
最后一个3的倍数是'12',它出现在索引4处。

这是我目前的代码。有人可以帮我修改我的代码吗?

public int findMultipleOfThree(int[] arr)
{
    int result = -1; // Initialize result to an invalid index
    for (int i = arr.length - 1; i >= 0; i--)
    {
        if(arr[i] % 3 == 0)
        {
            result = i; // Update result with the index of the multiple of three
            break; // No need to continue searching
        }
    }
    return result;
}

我知道这离正确的答案还有很远。请帮忙修改。

英文:

Write a method that returns the index of the last value in the array that is a multiple of 3.

For example, in the array

[4, 7, 9, 7, 12]
the last multiple of three is ‘12’, which occurs at index 4.

This is my code so far. Could anyone help me revising my code?

public int findMultipleOfThree(int[] arr)
{
    int result = 0;
    for (int i = arr.length-1; i > 0; i--)
    {
        if(i%3==0)
        {
            result = arr[i];
        }
    }
    return result;
}

I know this is far from the right answer. Please help

答案1

得分: 4

问题

您已经交换了用于比较和结果的元素,您需要:

  • 检查值 if (arr[i] % 3 == 0)
  • 返回索引 result = i

解决方案

  • 最佳方法: 您可以从末尾开始,返回第一个匹配的值,从而进行最小迭代

      public static int findMultipleOfThreeBackward(int[] arr) {
          for (int i = arr.length - 1; i > 0; i--) {
              if (arr[i] % 3 == 0) {
                  return i;
              }
          }
          return -1;
      }
    
  • 您可以从开头开始,覆盖 result 以返回最后一个匹配的值

     public static int findMultipleOfThreeForward(int[] arr) {
          int result = 0;
          for (int i = 0; i < arr.length; i++) {
              if (arr[i] % 3 == 0) {
                  result = i;
              }
          }
          return result;
      }
    

注意

我还建议使用 -1,因为它是一个无效的索引,它显示您没有找到任何与条件匹配的值。

英文:

Problem

You have switched the element for comparison and result, you need to

  • check the value if (arr[i] % 3 == 0)
  • return the indice result = i

Solution

  • best: you can do it from the end, and return the first match, you do the minimum iteration

      public static int findMultipleOfThreeBackward(int[] arr) {
          for (int i = arr.length - 1; i &gt; 0; i--) {
              if (arr[i] % 3 == 0) {
                  return i;
              }
          }
          return -1;
      }
    
  • You can do it from the beginning and override result to return the last one

     public static int findMultipleOfThreeForward(int[] arr) {
          int result = 0;
          for (int i = 0; i &lt; arr.length; i++) {
              if (arr[i] % 3 == 0) {
                  result = i;
              }
          }
          return result;
      }
    

Note

I'd also suggest to use -1, as it's an unvalid index, it shows you did not find any value that matches the condition

答案2

得分: 2

你的解决方案几乎是有效的!你需要添加一个break,但我看到其他人已经注意到了这一点。这里是另一种简单的方法来实现(不一定是最高效的)。

遍历整个数组,检查当前元素是否是3的倍数。将最大的索引存储在一个变量中,并且每当你找到一个更大的值时进行更新。返回arr[max_index]。代码应该类似于这样,希望我能帮到你。

public static int findMultipleOfThree(int[] arr)
{
    int max_index = -1; // 如果没有找到3的倍数,将返回-1
    for (int i = 0; i < arr.length-1; i++)
    {
        if(arr[i] % 3 == 0)
        {
           if(i > max_index)
             max_index = i;
             break;  // 添加break在这里
        }
    }
    return arr[max_index];
}
英文:

Your solution almost works! You need to add a break, but I see others have already noticed this. Here is another simple way to do it (not always the most efficient).
Iterate through the whole array and check if the current element is a multiple of 3. Store the max index in a variable and update every time you find a larger value. Return arr[max_index]. The code should look something like this, hope I could help you.

    public static int findMultipleOfThree(int[] arr)
{
    int max_index = -1; //if it does not find a multiple of 3 it will return -1
    for (int i = 0; i &lt; arr.length-1; i++)
    {
        if(arr[i]%3==0)
        {
           if(i&gt;max_index)
             max_index = i;

        }
    }
    return arr[max_index];
}

答案3

得分: 1

更新为

    public class Testing {
        public static void main(String[] args) {
            int[] arr = new int[] { 4, 7, 9, 7, 12 };
            System.out.println(findMultipleOfThree(arr));

        }

        public static int findIndexMultipleOfThree(int[] arr) {
            int index = 0;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] % 3 == 0) {
                    index = i;
                }
            }
            return index;
        }

    }

输出结果

    4
英文:

Update to this :

public class Testing {
	public static void main(String[] args) {
		int[] arr = new int[] { 4, 7, 9, 7, 12 };
		System.out.println(findMultipleOfThree(arr));

	}

	public static int findIndexMultipleOfThree(int[] arr) {
		int index = 0;
		for (int i = 0; i &lt; arr.length; i++) {
			if (arr[i] % 3 == 0) {
				index = i;
			}
		}
		return index;
	}

}

Output :

4

答案4

得分: 1

差不多可以了,你应该在这一行之后加上一个中断:

result = arr[i];

并且将这部分代码进行修改:

i%3==0

改成这样:

arr[i]%3==0

这样你肯定会找到最后一个。另外,你的 i 应该从 arr.length-1 开始,到 i >= 0,因为列表从 0 开始。

英文:

It's almost ok, you shoud put a break after this line:

result = arr[i];

And change this:

i%3==0

into this:

arr[i]%3==0

Thus you certainly find the last one. Also, your i should go from arr.length-1 to i >=0, since lists begin at 0

答案5

得分: 1

只需以相反顺序循环遍历值,并在找到倍数时立即返回。如果找不到任何内容并且循环完成,则返回 -1。此外,您可以修改方法签名以传入任何倍数值,例如 3

public class HelloWorld {
    public static void main(String... args) {
        int[] values = { 4, 7, 9, 7, 12 };
        
        System.out.println(findIndexForLastMultipleOf(3, values)); // 4
    }
     
    public static int findIndexForLastMultipleOf(int target, int... values) {
        for (int i = values.length - 1; i >= 0; i--) {
            if (values[i] % target == 0) {
                return i;
            }
        }
        return -1;
    }
}

如果您要定位一个值,而不是索引,您会返回什么?您应该将 int 包装成 Integer,如果没有找到倍数,返回 null。如果决定使用流过滤数组,还可以返回一个 Optional<Integer>

public class MathUtils {
    public static void main(String... args) {
        int[] values = { 4, 7, 9, 7, 12 };
        
        System.out.println(findLastMultipleOf(3, values)); // 12
    }
     
    public static Integer findLastMultipleOf(int target, int... values) {
        for (int i = values.length - 1; i >= 0; i--) {
            if (values[i] % target == 0) {
                return values[i];
            }
        }
        return null;
    }
}
英文:

Just loop through the values in reverse and immediatley return upon finding a multiple. If nothing is found and the loop is done, return -1. Additionally, you could modify the method signature to pass in any multiple value e.g. 3.

public class HelloWorld {
    public static void main(String... args) {
        int[] values = { 4, 7, 9, 7, 12 };
        
        System.out.println(findIndexForLastMultipleOf(3, values)); // 4
    }
     
    public static int findIndexForLastMultipleOf(int target, int... values) {
        for (int i = values.length - 1; i &gt;= 0; i--) {
            if (values[i] % target == 0) {
                return i;
            }
        }
        return -1;
    }
}

If you are locating a value, rather than an index, what do you return? You should box your int into an Integer and return null if nothing is a multiple. You could also return an Optional&lt;Integer&gt;, if you decide to stream-filter the array.

public class MathUtils {
    public static void main(String... args) {
        int[] values = { 4, 7, 9, 7, 12 };
        
        System.out.println(findLastMultipleOf(3, values)); // 12
    }
     
    public static Integer findLastMultipleOf(int target, int... values) {
        for (int i = values.length - 1; i &gt;= 0; i--) {
            if (values[i] % target == 0) {
                return values[i];
            }
        }
        return null;
    }
}

huangapple
  • 本文由 发表于 2020年9月24日 02:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64034513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定