There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
Example:
Input: n=7, ar[]={1,2,1,2,1,3,2}
Output: 2
Approach
Java
public class SalesMatch {public static void main(String[] args) {int n = 7;int[] ar = { 1, 2, 1, 2, 1, 3, 2 };System.out.println(sockMerchant(n, ar));}static int sockMerchant(int n, int[] ar) {int i, sum = 0;int c[] = new int[101], m[] = new int[101];for (i = 0; i <= 100; i++) {c[i] = 0;m[i] = 0;}for (i = 0; i < n; i++)c[ar[i]]++;for (i = 0; i <= 100; i++) {if (c[i] >= 2) {m[i] = c[i] / 2;}}for (i = 0; i <= 100; i++) {sum = sum + m[i];}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;int sockMerchant(int n, vector<int> ar){int i, sum = 0;int c[101], m[101];for (i = 0; i <= 100; i++){c[i] = 0;m[i] = 0;}for (i = 0; i < n; i++)c[ar[i]]++;for (i = 0; i <= 100; i++){if (c[i] >= 2){m[i] = c[i] / 2;}}for (i = 0; i <= 100; i++){sum = sum + m[i];}return sum;}int main(){int n = 7;vector<int> ar = {1, 2, 1, 2, 1, 3, 2};cout << sockMerchant(n, ar);return 0;}
No comments:
Post a Comment