求助!!!有关数组重复数据统计的问题

zhx0114 2018-04-18 06:45:25
题目:写一个Java程序,输入参数为一个int类型的数组,统计出int数组中值相等的所有元素,打印出值和元素所在的位置。
输入样例:值:2----位置:1,4,6
值:6----位置:2,3,72
值:28---位置:9,14,15
...全文
714 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_40030803 2018-04-19
  • 打赏
  • 举报
回复
public static void main(String[] args) { int[] m = { 1, 3, 6, 5, 7, 1, 5, 6, 1, 6 }; test(m); } static void test(int [] m){ Map<Integer,String> a = new Hashtable<>(); for (int i = 0; i < m.length; i++) { a.put(m[i],a.get(m[i]) == null ? i+"" : a.get(m[i])+","+i); } Iterator<Map.Entry<Integer, String>> iterator = a.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<Integer, String> entry = iterator.next(); System.out.println("值:" + entry.getKey()+ "位置:" + entry.getValue()); } }
zhx0114 2018-04-18
  • 打赏
  • 举报
回复
package doit;

import java.util.HashSet;
import java.util.Set;

public class xxx {
	public static void main(String[] args) {
		int[] m = { 1, 3, 6, 5, 7, 1, 5, 6, 1, 6 };
		test(m);
	}
	static void test(int [] m){
		Set s = new HashSet();
		for (int i = 0; i < m.length; i++) {
			int count = 1;
			for (int j = 0; j < m.length; j++) {
				if (m[i] == m[j] && i!=j) {
					count++;
					s.add(i);
					s.add(j);
				}
			}
			if (count > 1) {
				System.out.println("值:" + m[i] + "位置:" + s.toString());
				s=new HashSet();
			}
		}
	}
}
还是有问题,会重复输出
zhx0114 2018-04-18
  • 打赏
  • 举报
回复
package doit;
public class XXX {
	public static void main(String[] args) {
		int [] m = {1,3,5,6,7,1,5,6,1,6};	
		for (int i = 0; i < m.length; i++) {
			boolean bo =false;
			int a=0;
			int b=0;
			int c=0;
			for (int j = 0; j < m.length ; j++) {
				if(m[i]==m[j]){
					if(i!=j){
						bo=true;
						a=i;
						b=j;
						break;
					}
				}
			}
			for (int k = b+1; k < m.length; k++) {
				if(m[a]==m[k]){
					bo=true;
					c=k;
					break;
				}
			}
			if(bo){
				if(c!=a && c!=b){
					System.out.println("值:"+m[i]+"位置:"+a+","+b+","+c);					
				}
			}
		}
	}
}
代码还存在漏洞,求指点
zhx0114 2018-04-18
  • 打赏
  • 举报
回复
能不能 用一个双重的for循环解决呢?
oyljerry 2018-04-18
  • 打赏
  • 举报
回复
用链表做hashmap的值每个元素的位置做值插入链表

50,639

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧